Java流合并和输出

问题描述 投票:2回答:1

我有以下形式的对象列表:

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() );
}

我有没有办法在转换为最终列表之前不需要收集到中间表的方法?

java stream guava
1个回答
0
投票

您可以这样做:

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());
}
© www.soinside.com 2019 - 2024. All rights reserved.