Reputation: 2468
Let's assume that we have some Map
structere like below:
Map<Type, Map<String, String>> outterMap = new HashMap<>();
Map<String, String> innerMap1 = new HashMap<>();
innerMap1.put("1", "test1");
innerMap1.put("2", "test2");
innerMap1.put("3", "test3");
innerMap1.put("4", "test4");
Map<String, String> innerMap2 = new HashMap<>();
innerMap2.put("5", "test5");
innerMap2.put("6", "test6");
innerMap2.put("3", "test7");
outterMap.put(Type.TEXT, innerMap1);
outterMap.put(Type.INTEGER, innerMap2);
and we would like to print all values from innerMap with assigned Type
enum. With foreach loop it would look like this:
for (Type type : outterMap.keySet()) {
for (String value : outterMap.get(type).values()) {
if(type.equals(Type.TEXT)) {
System.out.println("TEXT: " + value);
}else if(type.equals(Type.INTEGER)) {
System.out.println("INTEGER: " + value);
}
}
}
So the output on console would looks like this:
TEXT: test1
TEXT: test2
TEXT: test3
TEXT: test4
INTEGER: test7
INTEGER: test5
INTEGER: test6
Is there any option to write it with help of the streams. I was able to use stream with lambda, and it looks like this:
outterMap.keySet().stream().forEach(type -> {
outterMap.get(type)
.values()
.stream()
.forEach(value -> {
if(type.equals(Type.TEXT)) {
System.out.println("TEXT: " + value);
} else if (type.equals(Type.INTEGER)) {
System.out.println("INTEGER: " + value);
}
});
});
Upvotes: 3
Views: 1778
Reputation: 1772
What about
outterMap.keySet().forEach(type -> outterMap.get(type)
.values()
.stream()
.map(value -> transform(type, value))
.forEach(System.out::println));
And
String transform(final Scratch.Type type, final String value) {
return type + ": " + value;
}
Upvotes: 0
Reputation: 16908
You can stream on the outer Map#entrySet
and get each entry and print out the key of the outer Map.Entry
and values of the inner Map
in the forEach()
callback:
outterMap.entrySet()
.stream()
.forEach(e -> e.getValue()
.values()
.forEach(v -> System.out.println(e.getKey()+ " " + v)));
Output:
TEXT test1
TEXT test2
TEXT test3
TEXT test4
INTEGER test7
INTEGER test5
INTEGER test6
Upvotes: 0
Reputation: 120848
Probably this:
outterMap.keySet()
.stream()
.flatMap(x -> outterMap.getOrDefault(x, Collections.emptyMap())
.values()
.stream()
.map(y -> new SimpleEntry<>(x, y)))
.forEachOrdered(entry -> {
System.out.println(entry.getKey() + " " + entry.getValue());
});
But this is by far less readable than what you have.
Upvotes: 3