java - 我可以内联这些流运算符序列吗?
问题描述
我有以下代码:
public List<PolygonStat> groupItemsByTypeAndWeight(List<Item> items)
{
Map<Type, List<Item>> typeToItem = items
.stream()
.collect(
Collectors.groupingBy(
item -> item.type,
Collectors.toList()
)
);
// For some reason we want to make a distinction between weighted items within type
ArrayList<WeightedItem> weightedItems = new ArrayList<>();
typeToItem.forEach(
// List to list function
(type, items) -> weightedItems.addAll(createWeightedList(type, items))
);
return weightedItems;
}
我真的不喜欢我ArrayList<WeightedItem> weightedItems = new ArrayList<>();
在这里的创作方式。是否有机会将其简化为一个return
运算符(即:return items.stream().(...).toList()
。我考虑过使用flatMap
but forEach
for .entrySet
should return void
。
解决方案
您可以不将中间结果保存到地图中,而只需从其 entrySet 创建一个新流。然后通过使用该map()
操作,您可以将每个条目映射到新的WeightedItem
.
public List<PolygonStat> groupItemsByTypeAndWeight(List<Item> items){
return items.stream()
.collect(Collectors.groupingBy(item -> item.type))
.entrySet()
.stream()
.map(entry -> createdWeightedList(entry.getKey(), entry.getValue()))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
推荐阅读
- javascript - 为什么我使用 moment.js 得到一个无限循环?
- r - 沿线串查找坐标 x 距离
- python-3.x - 连接到远程烧瓶服务器并获取输出
- asp.net-web-api - 为什么在使用访问令牌时会得到一个 HTML 页面作为响应,而在使用 ID 令牌时会得到想要的结果?(天青广告)
- vb.net - 如何在 vb.net 中从 Form 1 打开 Form 2 并关闭 Form 1
- c# - 具有实例变量的静态类一直有效,直到我将另一个变量引入到静态的静态类中
- git - 使用 Jenkins 将一个 git 存储库镜像到另一个存储库
- arrays - 如何在bash for循环中读取数组的单个项目
- anylogic - 系统动力学中累积和的 AnyLogic 变量
- installation - install clFFT library on ubuntu for opencl programs