Last active
October 11, 2023 19:41
-
-
Save dataduke/c37785410de3235e259805f0752e946e to your computer and use it in GitHub Desktop.
Flatten a nested Map
This file contains hidden or 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
import java.util.Map; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class Maps { | |
public static Map<String, Object> asFlattendMap(Map<String, Object> map) { | |
return map.entrySet().stream() | |
.flatMap(Maps::flatten) | |
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); | |
} | |
private static Stream<Map.Entry<String, ?>> flatten(Map.Entry<String, ?> entry) { | |
if (entry.getValue() instanceof Map) { | |
return ((Map<String,?>) entry.getValue()).entrySet().stream().flatMap(Maps::flatten); | |
} | |
return Stream.of(entry); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment