[英]Java stream merge and output
我有一個表單對象列表:
public class Child
{
private Mom mom;
private Dad dad;
private String name;
private int age;
private boolean isAdopted;
}
我需要將此列表轉換為不同數據結構的列表,將具有相同媽媽和爸爸鍵的對象聚合到表單中
public class Family
{
private Mom mom;
private Dad dad;
private Map<String, int> kids;
}
其中“兒童”地圖是所有兒童姓名到年齡的地圖。
目前,我正在做這個翻譯如下:
public Collection<Family> transform( final Collection<Child> children )
{
return children.stream()
.filter( child -> !child.getIsAdopted() )
.collect( ImmutableTable.toImmutableTable( child -> child.getMom(),
child -> child.getDad(),
child -> new HashMap<>(child.getName(), child.getAge() ),
(c1, c2) -> {
c1.getKids().putAll(c2.getKids());
return c1;
} ) )
.cellSet()
.stream()
.map( Table.Cell::getValue)
.collect( Collectors.toList() );
}
有沒有辦法讓我在轉換到最終列表之前不需要收集到中間表?
如果您可以定義具有mom
和dad
屬性的GroupingKey
,則實現可以簡化為:
@Getter
@AllArgsConstructor
class GroupingKey {
Mom mom;
Dad dad;
}
public List<Family> transformer( final Collection<Child> children ) {
return children.stream()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(c -> new GroupingKey(c.getMom(), c.getDad())),
map -> map.entrySet().stream()
.map(e -> new Family(e.getKey().getMom(), e.getKey().getDad(),
e.getValue().stream().collect(Collectors.toMap(Child::getName, Child::getAge))))
.collect(Collectors.toList())));
}
或者如果不是通過定義任何其他類,您可以使用與以下相同的方法轉換對象:
public List<Family> transform( final Collection<Child> children ) {
return children.stream()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(c -> Arrays.asList(c.getMom(), c.getDad())),
map -> map.entrySet().stream()
.map(e -> new Family(((Mom) ((List) e.getKey()).get(0)), ((Dad) ((List) e.getKey()).get(1)),
e.getValue().stream().collect(Collectors.toMap(Child::getName, Child::getAge))))
.collect(Collectors.toList())));
}
你可以這樣做:
public static Collection<Family> transform( final Collection<Child> children ) {
Map<Mom, Map<Dad, Family>> families = new HashMap<>();
for (Child child : children) {
if (! child.isAdopted()) {
families.computeIfAbsent(child.getMom(), k -> new HashMap<>())
.computeIfAbsent(child.getDad(), k -> new Family(child.getMom(), child.getDad(), new HashMap<>()))
.getKids().put(child.getName(), child.getAge());
}
}
return families.values().stream().flatMap(m -> m.values().stream()).collect(Collectors.toList());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.