我有以下两个课程:
public class Child {
private String name;
private int roll;
private int age;
private Date dob;
. . . .
getters and setters
. . . .
}
public class Parent {
private String name;
private int age;
private List<Child> children;
. . . .
getters and setters
. . . .
}
现在我有一个List<Child>
作为输入。我想根据名称和年龄属性对列表进行分组,并使用List<Parent>
生成List.stream()
。任何指针将不胜感激,并在此先感谢。
编辑:
Parent
和Child
类之间的映射为Parent.name
等于Child.name
,而Parent.age
等于Child.age
(用于分组的属性);
答案 0 :(得分:0)
您可以通过两个Map<String, Map<Integer, List<Child>>>
收藏家获得groupingBy
:
Map<String, Map<Integer, List<Parent>>> grouped =
input.stream()
.collect(Collectors.groupingBy(Child::getName,
Collectors.groupingBy(Child::getAge)));
此Map
可用于生成Parent
实例:
List<Parent> parents =
grouped.entrySet()
.stream()
.flatMap(e1 -> e1.getValue()
.entrySet()
.stream()
.map(e2 -> new Parent(e1.getKey(),e2.getKey(),e2.getValue())))
.collect(Collectors.toList());
假设存在一个接受名称,年龄和Parent
的{{1}}构造函数。