开发者

Set operations on Map

How can one perform开发者_Python百科 set operations on a HashMap, such as Collections.addAll()?


Based on you comments to the questions asked I think what you really need is a Set not a Map.

Try

Set<String> mySet = new HashSet<String>();
mySet.addAll(...);

Use mySet.contains("someString"); for quick determination if a value exists. It should be equivalent of what you seem to be trying to do.


Through for instance Map.putAll.

You may also be able to do set-operations directly on the set of map entries which you can get hold of through Map.entrySet.

From the documentation:

Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.


This way:

hashMap.putAll(map);

From documentation:

Copies all of the mappings from the specified map to this map These mappings will replace any mappings that this map had for any of the keys currently in the specified map.


You can do operations like

Map<String, String> map = new HashMap<String, String>();
Set<String> set = map.keySet();
for(String s: set);
set.retainAll(set2); // keeps the keys in set2
set.removeAll(set3); // removes the keys in set3
set.remove(s);

You can also turn a Map in a Set. There is no ConcurrentHashSet but you can do

Set<String> set = Collections.setFromMap(new ConcurrentHashMap<String, Boolean>());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜