Java stream collect to map with multiple keys

Garret Wilson picture Garret Wilson · Jun 22, 2016 · Viewed 10.2k times · Source

I thought I was getting pretty good at Java 8 streams, but then...

I have a Foo interface:

public interface Foo {
  String getKey();
  Stream<Bar> bars();
}

I know I can collect a Stream<Foo> into a Map<String, Foo> using the key of each:

Map<String, Foo> foosByKey = fooStream.collect(
    Collectors.toMap(Foo::getKey, Function.identity()));

But what if I want to collect them into a Map<Bar, Foo>? In other words, for each Foo in the steam, I want to put that Foo in the map keyed to every one of the Bar instances returned by Foo.bars(). Where do I start?

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Jun 22, 2016

As suggested here, you'll want extract the Bar values from each Foo and create pairs of them. Once you have the pairs, you can collect them into a Map. For example,

Map<Bar, Foo> map = fooStream.flatMap(foo -> foo.bars().map(bar -> new SimpleEntry<>(bar, foo)))
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); 

We use SimpleEntry here because it's available (Java doesn't have a simpler Pair type). You could write your own to be more specific.