让我们假设我们有一些Map
结构,如下所示:
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);
我们想打印来自 innerMap 的所有值,并分配Type
枚举。使用 foreach 循环,它看起来像这样:
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);
}
}
}
因此,控制台上的输出如下所示:
TEXT: test1
TEXT: test2
TEXT: test3
TEXT: test4
INTEGER: test7
INTEGER: test5
INTEGER: test6
是否有任何选项可以在流的帮助下编写它。我能够将流与lambda一起使用,它看起来像这样:
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);
}
});
});
大概是这个:
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());
});
但这远不如您拥有的可读性。
您可以在外部Map#entrySet
上流式传输并获取每个条目,并在forEach()
回调中打印出外部Map.Entry
的键和内部Map
的值:
outterMap.entrySet()
.stream()
.forEach(e -> e.getValue()
.values()
.forEach(v -> System.out.println(e.getKey()+ " " + v)));
输出:
TEXT test1
TEXT test2
TEXT test3
TEXT test4
INTEGER test7
INTEGER test5
INTEGER test6
怎么样
outterMap.keySet().forEach(type -> outterMap.get(type)
.values()
.stream()
.map(value -> transform(type, value))
.forEach(System.out::println));
和
String transform(final Scratch.Type type, final String value) {
return type + ": " + value;
}