Created
July 3, 2018 07:50
-
-
Save exceptionplayer/ef0a54d016540bf604f94541eb490b9f to your computer and use it in GitHub Desktop.
how to flatten a nested map in java8
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
public void testFlattenMap() { | |
Map<String, Map<String, Long>> counters = new HashMap<>(); | |
Map<String, Long> nested = new HashMap<>(); | |
nested.put("inner1", 1L); | |
nested.put("inner2", 2L); | |
nested.put("inner3", 3L); | |
counters.put("out1", nested); | |
counters.put("out2", nested); | |
counters.put("out3", nested); | |
//change the counters map to Map<String,Long> | |
// the keys are like: out1.inner1,out1.inner2 ... | |
Stream<SimpleEntry<String, Long>> entryStream = counters.entrySet().stream() | |
.flatMap(e -> e.getValue().entrySet().stream().flatMap( | |
v -> Stream.of(new SimpleEntry<>(e.getKey() + "." + v.getKey(), v.getValue())))); | |
Map<String, Long> collect = entryStream | |
.collect(Collectors.toMap(Entry::getKey, Entry::getValue)); | |
collect.forEach((k, v) -> { | |
System.out.println("k:" + k + ",v:" + v); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
notes: read the java docs about Stream.map and Stream.flatMap carefully, the difference is here:
Steam.map does not replace the streams, it only do something on the elements of the stream.
Strem.flatMap replaces the elements of the stream with another stream, the new stream is produced by the function you provided
In a nutshell, Stream.map does not replace elements with streams, it works on the elements of the stream, Stream.flatMap replace elements with steams.