If the keys of the inner map should be filtered, this can be done like this:
static List<Integer> findByKey(Map<String, Map<String, List<Integer>>> map, String key) {
return map.values()
.stream() // Stream<Map<String, List<Integer>>>
.flatMap(v -> v.entrySet().stream()) // Stream<Map.Entry<String, List<Integer>>>
.filter(e -> key.equals(e.getKey()))
.flatMap(e -> e.getValue().stream()) // Stream<Integer>
.collect(Collectors.toList());
}
Test
Map<String, Map<String, List<Integer>>> map = Map.of(
"KeyA", Map.of("keya", Arrays.asList(1, 2, 3)),
"KeyB", Map.of("keya", Arrays.asList(4, 5, 6)),
"KeyC", Map.of("keyb", Arrays.asList(7, 8))
);
System.out.println(findByKey(map, "keya"));
Output changes randomly
[4, 5, 6, 1, 2, 3]
or
[1, 2, 3, 4, 5, 6]
This output occurs randomly the mixed order, because the input map is not sorted and this can be resolved by sorting the stream of entrySet of the input map:
static List<Integer> findByKeySorted(Map<String, Map<String, List<Integer>>> map, String key) {
return map.entrySet()
.stream() // Stream<Map.Entry<String, Map<List<Integer>>>>
.sorted(Map.Entry.comparingByKey())
.map(e -> e.getValue().get(key)) // Stream<List<Integer>>
.filter(Objects::nonNull)
.flatMap(List::stream) // Stream<Integer>
.collect(Collectors.toList());
}
System.out.println(findByKeySorted(map, "keya"));
Output (stable):
[1, 2, 3, 4, 5, 6]
Map<String, Map<Integer, List<Integer>>>orMap<String, Map<String, List<Integer>>>? Rewrite example