使用流API分组时,多个组中的单个元素 [英] Single element in multiple groups when grouping with stream API

查看:44
本文介绍了使用流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);
        }
    }
}

我计划使用流API中的分组替换它,但我遇到了麻烦.对于我的第二个条件,它可以正常工作,但是如何处理第一个条件,即应将项目添加到接受此类项目的每个组中?真的有可能,还是我在这里与失落的原因作斗争?

I planned to replace it using grouping from stream API, but I'm stuck. 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?

推荐答案

您可以创建所有有效组ID和项目对,然后按组ID对它们进行分组:

You can create pairs of all the valid group IDs and Items, and then group them by group 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())));

这篇关于使用流API分组时,多个组中的单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆