Java Tree Map 打印值说明
Java Tree Map print value clarification
我的问题
在打印映射值时我想打印哪个键具有多个值
详情如下
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);
});
});
可以申请filter
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]
您为此使用流是否有特殊原因?标准命令式格式更易于编写和阅读:
for (Entry<Integer, Set<String>> e : myMap.entrySet()) {
if (e.getValue().size() > 1) {
System.out.println(e.getKey());
for (String s : e.getValue()) {
System.out.println(" " + s);
}
}
}
当然,还有几行,但简洁不一定是一种美德。清晰度应该是您最关心的问题。
我的问题
在打印映射值时我想打印哪个键具有多个值
详情如下
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);
});
});
可以申请filter
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]
您为此使用流是否有特殊原因?标准命令式格式更易于编写和阅读:
for (Entry<Integer, Set<String>> e : myMap.entrySet()) {
if (e.getValue().size() > 1) {
System.out.println(e.getKey());
for (String s : e.getValue()) {
System.out.println(" " + s);
}
}
}
当然,还有几行,但简洁不一定是一种美德。清晰度应该是您最关心的问题。