我需要使用特定对象的属性(Location)对对象列表(Student)进行分组,代码如下所示,
public class Grouping {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
studlist.add(new Student("4321", "Max", "California"));
studlist.add(new Student("2234", "Andrew", "Los Angeles"));
studlist.add(new Student("5223", "Michael", "New York"));
studlist.add(new Student("7765", "Sam", "California"));
studlist.add(new Student("3442", "Mark", "New York"));
//Code to group students by location
/* Output should be Like below
ID : 1726 Name : John Location : New York
ID : 5223 Name : …Run Code Online (Sandbox Code Playgroud) 我有兴趣从流中排序列表.这是我正在使用的代码:
list.stream()
.sorted((o1, o2)->o1.getItem().getValue().compareTo(o2.getItem().getValue()))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?该列表没有排序.
它应该根据具有最低值的项目对列表进行排序.
for (int i = 0; i < list.size(); i++)
{
System.out.println("list " + (i+1));
print(list, i);
}
Run Code Online (Sandbox Code Playgroud)
和打印方法:
public static void print(List<List> list, int i)
{
System.out.println(list.get(i).getItem().getValue());
}
Run Code Online (Sandbox Code Playgroud) 我有简单对象的列表:
private String unit;
private Double value;
Run Code Online (Sandbox Code Playgroud)
列表看起来像这样:
f, 1.0;
ml, 15.0;
g, 9.0
Run Code Online (Sandbox Code Playgroud)
我创建了一个简单的函数,希望将这些值分组并以unit为键将它们放入地图,并将对象列表作为值,但是我想像在原始列表中那样保存顺序。这是我目前的解决方案:
myList.stream()
.collect(groupingBy(MyObject::getUnit));
Run Code Online (Sandbox Code Playgroud)
但是之后,我的地图按字母顺序排序:f,g,ml,而不是f,ml,g。有没有其他分组方法可以解决?