Java 8 lambdas 将列表分组到映射中 - 如果每个键有多个列表项,则不同的键

我有一个关系列表。每个关系对象都有三个变量:personA、personB 和 relationshipType。

relationshipType 对象有两个变量:relationship (Son) 和 relationshipPlural (Sons)

我有一个要求,我需要列出一个人的关系。如果一个人只有一个妻子,那就是:

Wife      <wifeName>

如果这个人有一个以上的儿子,那就是:

    Sons      <firstSonName>
              <secondSonName>

是否有一个简单的 lambda 表达式,我可以在其中将关系列表转换为map<String,List<relationship>>where 如果键具有包含多个项目的列表,则键值是 relationshipType.relationshipPlural 值?

我能想到的唯一选择是使用两个表达式,

1)Collectors.toMap()创建一个关系类型的地图,然后

2) 处理地图以创建另一个地图,如果地图的值是具有多个值的列表,则地图的键将为 relationshipType.relationshipPlural。


手掌心
浏览 70回答 1
1回答

慕姐8265434

您可以尝试使用collectingAndThenwith groupingByas downstream as :private Map<String, List<RelationShip>> groupAndMapRelationships(List<RelationShip> relationShips) {&nbsp; &nbsp;return relationShips.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.collectingAndThen(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.groupingBy(RelationShip::getRelationshipType),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;map -> map.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(e -> new AbstractMap.SimpleEntry<>(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.getValue().size() == 1 ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.getKey().getRelationship() : e.getKey().getRelationshipPlural(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;e.getValue()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));}我考虑过的最小 POJO 看起来像:@Getterclass RelationShip {&nbsp; &nbsp; String personA;&nbsp; &nbsp; String personB;&nbsp; &nbsp; RelationshipType relationshipType;}@Getterclass RelationshipType {&nbsp; &nbsp; String relationship;&nbsp; &nbsp; String relationshipPlural;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java