【发布时间】:2020-07-13 02:55:09
【问题描述】:
给定以下课程A:
public class A {
private int id; //this field is unique
private int a_1; //this field ain't unique
private String a_2;
private String a_3;
//setters + getters
}
我们可以将list 类型为A 的随机对象分组为它们各自的a_1:
Map<String, List<A>> sortedmap = list.stream()
.collect(Collectors.groupingBy(A::getA_1, Collectors.toList()));
现在给定两个类B 和C,例如:
public class B{
private int id; //this field is unique for all entities of type B
private String b_1;
private C b_C; //many objects of type B may have a reference to the same object of type C
//setters + getters
}
public class C{
private int id; //this field is unique for all entities of type C
private String c_1;
private D c_D; //many objects of type C may have a reference to the same object of type D
//setters + getters
}
public class D{
private int id; //this field is unique for all entities of type D
private String d_1;
private String d_2;
//setters + getters
}
我们如何通过它们各自的b_C.getC_D().getId() 字段对B 类型的随机对象列表进行排序?
【问题讨论】:
-
你可以使用
Comparator -
您的意思是“排序”(与问题标题不匹配)还是“组”?如果分组,答案真的是一样的,但你不能使用方法参考:
Collectors.groupingBy(b -> b.getB_C().getC_D().getId(), Collectors.toList()) -
@sprinter 是的排序,我编辑了线程。
-
@saka1029 返回类型是什么?我需要一个 Map
> 类型的地图,其中关键是 b.getB_C().getC_D().getId() -
您的意思是按
b_C.getC_D().getId()分组并按b_C.getC_D().getId()对分组列表进行排序?
标签: java collections java-stream