Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 347
user902383 Avatar asked Sep 07 '25 17:09

user902383


1 Answers

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())));
like image 176
Eran Avatar answered Sep 09 '25 19:09

Eran