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 betweenBar
andFoo
instances. ConsiderMap<CreditCardNumber, Person>
orMap<ISBN, Book>
, where a person can have multiple credit cards and a book can have multiple ISBNs. Nothing complicated here. – GermMap
is 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 eachFoo
can have manyBar
, and I want to mapBar
toFoo
. Cheers! – GermFoo
can have manyBar
and that allBar
s 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? – RegMap.Entry
instances with implicit instantiation of capturing lambda instances, so there is no improvement at all. – Reg