如何在哈希图中打印具有重复值的键? [英] How to print keys with duplicate values in a hashmap?
本文介绍了如何在哈希图中打印具有重复值的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个哈希映射,其中一些键指向相同的值.我想找到所有相等的值并打印相应的键.
I have a hashmap with some keys pointing to same values. I want to find all the values that are equal and print the corresponding keys.
这是我当前拥有的代码:
This is the current code that I have:
Map<String, String> map = new HashMap<>();
map.put("hello", "0123");
map.put("hola", "0123");
map.put("kosta", "0123");
map.put("da", "03");
map.put("notda", "013");
map.put("twins2", "01");
map.put("twins22", "01");
List<String> myList = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
for (Map.Entry<String, String> entry2 : map.entrySet()){
if (entry.getValue().equals(entry2.getValue()))
{
myList.add(entry.getKey());
}
}
}
当前代码将重复项两次添加到列表中,但是也会将每个键一次添加一次.
The current code adds the duplicates two times into the list, however it also adds every key one time.
谢谢.
推荐答案
您可以使用流以这种方式检索重复项:
You can use streams to retrive duplicates in this way:
List<String> myList = map.stream()
.filter(n -> Collections.frequency(map.values(), n) > 1)
.collect(Collectors.toList());
然后,您可以使用以下命令将其打印出来:
And then, you can print this out with:
myList.foreach(System.out::println);
这篇关于如何在哈希图中打印具有重复值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文