Java 8 Stream "collect and group by" objects that map to multiple keys

I have the following objects:

public class Item {
    String value;
    List<Person> owners;
    Person creator;
}

public class Person {
    String name;
    int id;
    Person manager;
}

I now have a list containing 3 Item objects:

i1 -> {value="1", owners=[p1, p2, p3], creator=p4}
i2 -> {value="2", owners=[p2, p3], creator=p5}
i3 -> {value="3", owners=[p5], creator=p1}

Person objects are as follows:

p1 -> {manager=m1, ...}
p2 -> {manager=m2, ...}
p3 -> {manager=m3, ...}
p4 -> {manager=m2, ...}
p5 -> {manager=m1, ...}

I want to group a stream of Item objects based on the owners and creators managers. The result Map<Person, List<Item>>should look like this:

{
  m1: [i1, i2, i3],
  m2: [i1, i2],
  m3: [i1, i2]
}

I think that using the Stream and Collector APIs, I can first make the map from Item to managers Map<Item, List<Person>>, and then cancel the display. But is there a way to make the mapping that I want to use only Stream and Collectors?

+4
source share
2 answers

, "", / . API Javas Map.Entry, Pair:

Map<Person, List<Item>> map = list.stream()
  .flatMap(item->item.getOwners().stream()
    .map(p->new AbstractMap.SimpleEntry<>(p.getManager(), item)))
  .collect(Collectors.groupingBy(Map.Entry::getKey,
    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

import static

Map<Person, List<Item>> map = list.stream()
  .flatMap(item->item.getOwners().stream().map(p->new SimpleEntry<>(p.getManager(), item)))
  .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));

m1: [i1,i3]
m3: [i1,i2]
m2: [i1,i2]

, -, , -, , , m1 i2 .

+16

StreamEx, Stream API:

Map<Person, List<Item>> map = StreamEx.of(list) // create an enhanced stream of Item
                // create a stream of Entry<Item, manager>
                .cross(item -> item.getOwners().stream().map(Person::getManager))
                // swap keys and values to get stream of Entry<manager, Item>
                .invert()
                .grouping();

@Holger.

+2

Source: https://habr.com/ru/post/1611314/


All Articles