我不知道为什么不适合我。我在 map 上有一个空 key ,但我抓不到它们。
Map<String, Long> map = new TreeMap<>();
//put data
map.entrySet().stream().forEach(e -> {
if (e.getKey().equals("") || e.getKey().equals(" ") || e.getKey() == "" || e.getKey() == " ") {
map.remove(e.getKey(), e.getValue());
}
});
编辑: 我做了一个值(value)测试:
map.entrySet().stream() .forEach(e -> {
if (e.getValue() == 133835) {
System.out.println("key empty: " + e.getKey().isEmpty());
System.out.println("key: >" + e.getKey() + "<");
System.out.println("val: " + e.getValue());
}
});
map = map.entrySet().stream().filter(
p -> !"".equals(p.getKey().trim())).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
map.entrySet().stream() .forEach(e -> {
if (e.getValue() == 133835) {
System.out.println("key empty: " + e.getKey().isEmpty());
System.out.println("key: >" + e.getKey() + "<");
System.out.println("val: " + e.getValue());
}
});
结果是:
key empty: false
key: ><
val: 133835
key empty: false
key: ><
val: 133835
我认为这把 key 很重要)
最佳答案
尝试使用 e.getKey().trim().isEmpty()
关于Java:在 map 中查找空键:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27433072/