2 回答

TA貢獻1877條經驗 獲得超6個贊
您可以創建所有有效組 ID 和項的對,然后按組 ID 對它們進行分組:
Map<Long,List<Item>> groupedItems =
groups.stream()
.flatMap(g -> items.stream()
.filter(i -> isGroupAccepting(i.getId(),g) || g == i.getGroup())
.map(i -> new SimpleEnty<>(g,i))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));

TA貢獻1813條經驗 獲得超2個贊
如果您使用的是 Idk 9 或更高版本,請嘗試以下操作:Collectors.flatMapping
// import static java.util.stream.Collectors.*;
Map<Long, List<Item>> groupedItems = groups.stream()
.collect(groupingBy(Function.identity(),
flatMapping(
groupId -> items.stream()
.filter(item -> isGroupAccepting(item.getId(), groupId) || groupId == item.getGroup()),
toList())));
不確定為什么要嘗試用 lambdas/流 API 替換循環。對我來說,代碼看起來很棒。大多數時候,lambdas 代碼看起來很丑陋,更難理解。forfor
添加回答
舉報