3 回答

TA貢獻1853條經驗 獲得超6個贊
如果我們假設它DistGroup基于hashCode/equalsand size,color你可以這樣做:
bumperCars
.stream()
.map(x -> {
List<String> list = new ArrayList<>();
list.add(x.getCarCode());
return new SimpleEntry<>(x, list);
})
.map(x -> new DistGroup(x.getKey().getSize(), x.getKey().getColor(), x.getValue()))
.collect(Collectors.toMap(
Function.identity(),
Function.identity(),
(left, right) -> {
left.getCarCodes().addAll(right.getCarCodes());
return left;
}))
.values(); // Collection<DistGroup>

TA貢獻1815條經驗 獲得超13個贊
解決方案-1
只需將兩個步驟合并為一個:
List<DistGroup> distGroups = bumperCars.stream()
.collect(Collectors.groupingBy(t -> new SizeColorCombination(t.getSize(), t.getColor())))
.entrySet().stream()
.map(t -> {
DistGroup d = new DistGroup(t.getKey().getSize(), t.getKey().getColor());
d.addCarCodes(t.getValue().stream().map(BumperCar::getCarCode).collect(Collectors.toList()));
return d;
})
.collect(Collectors.toList());
解決方案-2
groupingBy如果您可以使用屬性兩次并將值映射為List代碼,那么您的中間變量會好得多,例如:
Map<Integer, Map<String, List<String>>> sizeGroupedData = bumperCars.stream()
.collect(Collectors.groupingBy(BumperCar::getSize,
Collectors.groupingBy(BumperCar::getColor,
Collectors.mapping(BumperCar::getCarCode, Collectors.toList()))));
并簡單地使用forEach添加到最終列表中:
List<DistGroup> distGroups = new ArrayList<>();
sizeGroupedData.forEach((size, colorGrouped) ->
colorGrouped.forEach((color, carCodes) -> distGroups.add(new DistGroup(size, color, carCodes))));
注意:我已經更新了您的構造函數,使其接受卡代碼列表。
DistGroup(int size, String color, List<String> carCodes) {
this.size = size;
this.color = color;
addCarCodes(carCodes);
}
進一步將第二個解決方案組合成一個完整的陳述(盡管我自己喜歡forEach老實說):
List<DistGroup> distGroups = bumperCars.stream()
.collect(Collectors.groupingBy(BumperCar::getSize,
Collectors.groupingBy(BumperCar::getColor,
Collectors.mapping(BumperCar::getCarCode, Collectors.toList()))))
.entrySet()
.stream()
.flatMap(a -> a.getValue().entrySet()
.stream().map(b -> new DistGroup(a.getKey(), b.getKey(), b.getValue())))
.collect(Collectors.toList());

TA貢獻1817條經驗 獲得超14個贊
查看我的圖書館AbacusUtil:
StreamEx.of(bumperCars) .groupBy(c -> Tuple.of(c.getSize(), c.getColor()), BumperCar::getCarCode) .map(e -> new DistGroup(e.getKey()._1, e.getKey()._2, e.getValue()) .toList();
添加回答
舉報