Skip to content

Instantly share code, notes, and snippets.

@kozake
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kozake/df659e28c135a3de2fb8 to your computer and use it in GitHub Desktop.
Save kozake/df659e28c135a3de2fb8 to your computer and use it in GitHub Desktop.
mapOfItemsToSuppliersByStream
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