有没有办法找出映射中具有相同值的所有键。 喜欢
map.put("A","Abc");
map.put("B","Abc");
map.put("C","Abc");
map.put("D","Bcd");
这里我想找出所有值为“Abc”的键。
最佳答案
找到所有“x”,使得“y”被称为 filtering
.
这就是你可以 filter using Java 8 Streams :
Stream<String> keys = map.entrySet().stream()
.filter(x -> "Abc".equals(x.getValue()))
.map(Map.Entry::getKey);
对于 Java 7,您必须手动执行此操作:
List<String> keys = new ArrayList<>();
for(Map.Entry<String, String> e : map.entrySet())
if("Abc".equals(e.getValue()))
keys.add(e.getKey());
关于Java查找所有具有特定值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30819627/