我有四個值a
,b
,c
,d
只有a
我想看看是否HashMap具有價值a
並打印一個HashMap和列表。HashMap和列表進行比較
hashmap.get('data')
結果a
,b
,c
,d
列表l
是有a
我怎麼會只打印值a
我有四個值a
,b
,c
,d
只有a
我想看看是否HashMap具有價值a
並打印一個HashMap和列表。HashMap和列表進行比較
hashmap.get('data')
結果a
,b
,c
,d
列表l
是有a
我怎麼會只打印值a
A地圖存儲鍵值對。它提供了一個values()
方法來獲取地圖中所有值的集合。
所以基本上你得把你自己的列表,從HashMap中獲得的價值和檢查列表中的每個項目,如果它是一個映射值:
public static Collection<String> contains(Map<String, String> map, List<String> list) {
Collection<String> values = map.values();
Set<String> result = new HashSet<String>();
for (String listItem:list) {
if (values.contains(listItem) {
result.add(listItem);
}
}
return result; // contains a collection of all list items that are values of the map
}
一個Java地圖(包括HashMap中)有一個鍵設置()方法來檢索密鑰。它返回一組鍵。如果您也將List轉換爲Set(通過使用帶有列表的HashMap構造函數),則可以使用Set的retainAll(...)方法從地圖的鍵和列表中獲取值的交集。
如果我正確理解你的問題,你可以使用地圖的values()
方法,結果的retainAll
方法解決這個問題:
HashMap<Integer, String> somePairs = new HashMap<Integer, String>();
somePairs.put(1, "a");
somePairs.put(2, "b");
somePairs.put(3, "c");
somePairs.put(4, "d");
List<String> list = Arrays.asList("a");
// Start off with all values in the map:
List<String> result = new ArrayList<String>(somePairs.values());
// Keep only those values present in list
result.retainAll(list);
從the API documentation on retainAll
:
只保留此集合中包含在指定集合中的元素(可選操作)。換句話說,從該集合中刪除所有未包含在指定集合中的元素。
基本上你想要的值聯盟在地圖hashmap
和列表l
中。 這應該做的伎倆:
CollectionUtils.union(hashmap.values(), l)
這需要在類路徑中,這對收藏了很多有用的功能Apache Commons Collections庫。