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?
Map<Bar, Foo>would imply a one-to-one mapping betweenBarandFooinstances. ConsiderMap<CreditCardNumber, Person>orMap<ISBN, Book>, where a person can have multiple credit cards and a book can have multiple ISBNs. Nothing complicated here.Mapis a unidirectional, so you can't map back---which is why Guava has aBiMap, for instance. I think you wanted to say that the relationship is one-to-one---in this case the relationship is many-to-one (Bar-Foo). But again this is all sort of beside the point---things to debate over a beer. The summary is that eachFoocan have manyBar, and I want to mapBartoFoo. Cheers!Foocan have manyBarand that allBars are distinct and, well, I think Sotirios’ answer contains an appropriate solution. Is there anything that stops you from accepting his answer, that we should address?Map.Entryinstances with implicit instantiation of capturing lambda instances, so there is no improvement at all.