Last active
August 29, 2015 14:23
-
-
Save kozake/df659e28c135a3de2fb8 to your computer and use it in GitHub Desktop.
mapOfItemsToSuppliersByStream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class Tuple<F, S> { | |
private F first; | |
private S second; | |
public static <F, S> Tuple<F, S> pair(F f, S s) { | |
return new Tuple<F, S>(f, s); | |
} | |
private Tuple(F first, S second) { | |
this.first = first; | |
this.second = second; | |
} | |
public F getFirst() { | |
return first; | |
} | |
public S getSecond() { | |
return second; | |
} | |
} | |
@Test | |
public void mapOfItemsToSuppliersByStream() | |
{ | |
final Map<String, List<Supplier>> itemsToSuppliersStream | |
= Stream.of(this.company.getSuppliers()) | |
.flatMap(supplier -> | |
Arrays.stream(supplier.getItemNames()) | |
.map(itemName -> Tuple.pair(itemName, supplier))) | |
.collect(Collectors.groupingBy(t -> t.getFirst(), | |
Collectors.mapping(t -> t.getSecond(), | |
Collectors.toList()))); | |
Verify.assertIterableSize( | |
"should be 2 suppliers for sofa", | |
2, | |
itemsToSuppliersStream.get("sofa")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment