将Set <Map.Entry >转换为HashMap
在我的代码中的某一点,我从地图创建了一个Set<Map.Entry>
。 现在我想重新创建相同的地图表单,所以我想将HashSet<Map.Entry>
回HashMap
。 Java是否有本机调用,或者我是否必须循环设置元素并手动构建映射?
在Java中没有用于HashSet
和HashMap
之间直接转换的内置API,您需要迭代set并使用Entry
fill in map。
一种方法:
Map map = new HashMap(); //fill in map Set> set = map.entrySet(); Map mapFromSet = new HashMap(); for(Entry entry : set) { mapFromSet.put(entry.getKey(), entry.getValue()); }
虽然这里的目的是什么,如果你在Set
中做任何更改,也会在Map
反映Map.entrySet
返回的Map.entrySet
是Map
备份。 见下面的javadoc
:
设置
> java.util.Map.entrySet() 返回此映射中包含的映射的Set视图。 该集由地图支持,因此对地图的更改将反映在集中,反之亦然。 如果在对集合进行迭代时修改了映射(除非通过迭代器自己的remove操作,或者通过迭代器返回的映射条目上的setValue操作),迭代的结果是未定义的。 该集支持元素删除,它通过Iterator.remove,Set.remove,removeAll,retainAll和clear操作从地图中删除相应的映射。 它不支持add或addAll操作。
涉及Collectors.toMap
更简单的Java-8解决方案:
Map mapFromSet = set.stream() .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
如果遇到重复键,将抛出IllegalStateException
。
相当简短的Java 8解决方案。 可以应付重复的键。
Map map = new HashMap<>(); //fill in map Set> set = map.entrySet(); Map mapFromSet = set.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a,b)->b));
编辑:感谢shmosel ,他应该得到比我更多的信任
从Guava 19开始,你可以使用ImmutableMap.copyOf(Iterable
从Java 9开始,我们有Map.ofEntries 。 它们只接受一个数组,所以你需要先用toArray()
转换它们并抛出类型信息。
@SuppressWarnings("unchecked") Map.Entry[] array = entrySet.toArray((Map.Entry[])new Map.Entry, ?>[entrySet.size()]); Map map = Map.ofEntries(array);
Apache Commons有类似的方法。 Commons Lang的ArrayUtils.toMap :
Map
Commons Collections的MapUtils.putAll :
Map map = MapUtils.putAll(new HashMap(), entrySet.toArray());
在Java 8中使用正确的组合器
Map map = new HashMap<>(); //fill in map Set> set = map.entrySet(); Map mapFromSet =set.stream().collect(HashMap::new,(t, u) -> t.put(u.getKey(), u.getValue()), (Map mapToReturn, Map otherMap) -> { otherMap.entrySet().forEach((Map.Entry entry) -> { mapToReturn.put(entry.getKey(),entry.getValue()); }); return mapToReturn;}););