Skip to content

Instantly share code, notes, and snippets.

@h0tk3y
Created January 11, 2016 11:36
Show Gist options
  • Select an option

  • Save h0tk3y/dbb3754e93e044f4e841 to your computer and use it in GitHub Desktop.

Select an option

Save h0tk3y/dbb3754e93e044f4e841 to your computer and use it in GitHub Desktop.
Maps inversion
public <A, B, C> Map<B, List<Pair<A, C>>> invertMap(Map<A, Map<B, C>> input) {
return input.entrySet().stream()
.flatMap(kv -> kv.getValue().entrySet().stream().map(vs -> new Pair<>(kv.getKey(), vs)))
.collect(Collectors.groupingBy(
it -> it.getValue().getKey(),
Collectors.mapping(
it -> new Pair<>(it.getKey(), it.getValue().getValue()),
Collectors.toList()
))
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment