問題描述
我想在 HashMap
中顯示值.HashMap
可能有重復(fù)的值(但不是重復(fù)的鍵),但我只想顯示一次值.
I want to display the values in a HashMap
. A HashMap
may have duplicate values (but not duplicate keys), but I want to display a value only once.
所以我應(yīng)該找出 Map
是否有重復(fù)值.我知道我們可以遍歷 Map
并使用 map.containsValue(value)
的返回布爾值.我想知道是否存在任何方法來查找地圖中的重復(fù)值,或者我們應(yīng)該自己編寫代碼?
So I should find whether the Map
has duplicate values. I know we can iterate over the Map
and use the return boolean of map.containsValue(value)
. I want to know whether any method exists to find duplicate values in map or we should I write code myself?
推薦答案
一個簡單的解決方案是將值列表的大小與值集進行比較.
A simple solution would be to compare the size of your values list with your values set.
// pseudo-code
List<T> valuesList = map.values();
Set<T> valuesSet = new HashSet<T>(map.values);
// check size of both collections; if unequal, you have duplicates
這篇關(guān)于在 Java Map 中查找重復(fù)值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!