首页 > 解决方案 > 我可以内联这些流运算符序列吗?

问题描述

我有以下代码:

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()。我考虑过使用flatMapbut forEachfor .entrySetshould return void

标签: javajava-stream

解决方案


您可以不将中间结果保存到地图中,而只需从其 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());
}

推荐阅读