简体   繁体   English

使用流API分组时,多个组中的单个元素

[英]Single element in multiple groups when grouping with stream API

I'm reviewing some old code, where I'm grouping elements. 我正在查看一些旧代码,在其中对元素进行分组。 It looks more or less like this: 看起来或多或少是这样的:

Map<Long,List<Items>> groupedItems = ...
for (long groupid : groups){
    for (Item item :items){
        if (isGroupAccepting(item.getId(),groupid) || groupid == item.getGroup()) {
            groupedItems.get(groupid).add(item);
        }
    }
}

I planned to replace it using grouping from stream API, but I'm stuck. 我计划使用流API中的分组替换它,但是我遇到了麻烦。 It works fine for my second condition, but how to deal with the first one, where item should be added to every group which accepts that kind of item? 对于我的第二个条件,它工作正常,但是如何处理第一个条件,即应将项添加到接受此类项的每个组中? Is it actually possible, or am I fighting a lost cause here? 实际上有可能吗,还是我在这里与失落的原因作斗争?

You can create pairs of all the valid group IDs and Items, and then group them by group ID: 您可以创建所有有效组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())));

Try Collectors.flatMapping if you're using Idk 9 or above: 如果您使用的是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())));

Not sure why you want to try replace for loop with lambdas/Stream APIs. 不确定为什么要尝试使用lambdas / Stream API替换for循环。 To me the for code looks great. 对我来说, for代码看起来很棒。 Most time, the lambdas code looks ugly and more difficult to understand. 大多数时候,lambdas代码看起来很丑陋,更难以理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM