1 回答

TA貢獻1813條經驗 獲得超2個贊
您可以嘗試使用collectingAndThenwith groupingByas downstream as :
private Map<String, List<RelationShip>> groupAndMapRelationships(List<RelationShip> relationShips) {
return relationShips.stream()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(RelationShip::getRelationshipType),
map -> map.entrySet().stream()
.map(e -> new AbstractMap.SimpleEntry<>(
e.getValue().size() == 1 ?
e.getKey().getRelationship() : e.getKey().getRelationshipPlural(),
e.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));
}
我考慮過的最小 POJO 看起來像:
@Getter
class RelationShip {
String personA;
String personB;
RelationshipType relationshipType;
}
@Getter
class RelationshipType {
String relationship;
String relationshipPlural;
}
添加回答
舉報