我的问题
在打印 map 值时我想打印哪个键有多个值
详情如下
static Map<Integer, Set<String>> myMap = new TreeMap<>();
Key value
1 a
b
c
2 d
3 e
4 f
g
h
基于以上 我只想打印 1 和 4 我们需要省略 2 和 3
打印
myMap.entrySet().forEach((e) -> {
System.out.println(e.getKey());
e.getValue().forEach((c) -> {
System.out.println(" " + c);
});
});
最佳答案
您可以应用过滤器
myMap.entrySet().stream().filter(entry -> entry.getValue().size() > 1).forEach...
例如,
public class Test {
public static void main(String[] args) {
Map<Integer, Set<String>> myMap = new TreeMap<>();
Set<String> set1 = new HashSet<>();
Set<String> set2 = new HashSet<>();
Set<String> set3 = new HashSet<>();
set1.add("1");
set1.add("2");
set1.add("3");
set2.add("2");
set3.add("1");
set3.add("2");
myMap.put(1, set1);//3 Elements
myMap.put(2, set2);//1 Element
myMap.put(3, set3);//2 Elements
myMap.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.filter(entry -> entry.getValue().size() > 1)
.forEach(System.out::println);
}
}
输出
1=[1, 2, 3]
3=[1, 2]
关于Java Tree Map打印值说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887277/