java - Java流合并和输出
问题描述
我有一个形式的对象列表:
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() );
}
有没有办法让我做到这一点,而无需在转换为最终列表之前收集到中间表?
解决方案
如果您可以定义GroupingKey
withmom
和dad
属性,则可以将实现简化为:
@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())));
}
推荐阅读
- python - Python中多线程调用的问题
- r - 错误:在 R 中读取 .xslm 文件时,openxlsx 只能读取 .xlsx 文件
- go - Watson [speech to text]:原始音频不能通过 websockets 工作,而是通过 http 接口工作
- javascript - 我们可以添加两个或多个相同类型的对象吗?
- php - 如何在 Swift 5 中将图像转换为纯黑白
- android - 无法实例化一个或多个类:java.lang.ClassNotFoundException: androidx.databinding.DataBinderMapperImpl
- cypress - 无法在赛普拉斯的测试中使用别名
- swift - 在 Swift 5 中将字符串转换为 Double/Float 会丢失大数的精度
- swift - 使用字典计算每张图片显示的次数(有人可以解释挑战 1 Project12 (HackingWithSwift))
- .net - 创建新用户时出错(Blazor、REST Api)