Map.Entry methods for streams
Tagir F. Valeev
amaembo at gmail.com
Sat Jan 16 02:59:26 UTC 2016
Hello!
Note that having single swap() method which just swaps key and value
in addition to withKey/withValue covers this use case:
Map<B, List<A>> gad = dag.entrySet()
.stream()
.flatMap(e -> e.getValue().stream().map(e.swap()::withKey))
.collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));
TK> For completeness, having also the methods
TK> default <NK> Entry<NK, K> withKeyAsValue(NK newKey) {
TK> return new AbstractMap.SimpleEntry<>(newKey, getKey());
TK> }
TK> public <NV> Entry<V, NV> withValueAsKey(NV newValue) {
TK> return new AbstractMap.SimpleEntry<>(getValue(), newValue);
TK> }
TK> would be useful when inverting a graph, for example:
TK> Map<A, List<B>> dag = //. . .
TK> Map<B, List<A>> gad = dag.entrySet()
TK> .stream()
TK> .flatMap(e ->
TK> e.getValue().stream().map(e::withKeyAsValue))
TK> .collect(groupingBy(Entry::getKey,
TK> mapping(Entry::getValue, toList())));
More information about the core-libs-dev
mailing list