gpt4 book ai didi

Java流合并与输出

转载 作者:行者123 更新时间:2023-12-01 19:44:25 25 4
gpt4 key购买 nike

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

public class Child
{
private Mom mom;
private Dad dad;
private String name;
private int age;
private boolean isAdopted;
}

我需要将此列表转换为不同数据结构的列表,将具有相同 Mom 和 Dad 键的对象聚合到表单中

public class Family
{
private Mom mom;
private Dad dad;
private Map<String, int> kids;
}

其中“ child ” map 是所有 child 姓名到年龄的 map 。

目前,我的翻译工作如下:

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

有没有办法让我在转换为最终列表之前不需要收集到中间表来执行此操作?

最佳答案

如果您可以使用 momdad 属性定义 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())));
}

关于Java流合并与输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59002319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com