转换集合<Map.Entry<K,V>>到HashMap<K,V>

Convert Setlt;Map.Entrylt;K, Vgt;gt; to HashMaplt;K, Vgt;(转换集合lt;Map.Entrylt;K,Vgt;gt;到HashMaplt;K,Vgt;)

本文介绍了转换集合<Map.Entry<K,V>>到HashMap<K,V>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我从地图创建了一个 Set.现在我想重新创建相同的地图形式,所以我想将 HashSet 转换回 HashMap<K, V>.Java 是否有执行此操作的本机调用,还是我必须循环设置元素并手动构建地图?

At one point in my code, I created a Set<Map.Entry<K, V>> from a map. Now I want to recreate the same map form, so I want to convert the HashSet<Map.Entry<K, V>> back into a HashMap<K, V>. Does Java have a native call for doing this, or do I have to loop over the set elements and build the map up manually?

推荐答案

HashSetHashMap之间没有直接转换的java内置API,需要迭代通过设置和使用Entry填写地图.

There is no inbuilt API in java for direct conversion between HashSet and HashMap, you need to iterate through set and using Entry fill in map.

一种方法:

Map<Integer, String> map = new HashMap<Integer, String>();
    //fill in map
    Set<Entry<Integer, String>> set = map.entrySet();

    Map<Integer, String> mapFromSet = new HashMap<Integer, String>();
    for(Entry<Integer, String> entry : set)
    {
        mapFromSet.put(entry.getKey(), entry.getValue());
    }

虽然这里的目的是什么,但如果您在 Set 中进行任何更改,这些更改也会反映在 Map 中,就像 Map.entrySetMap 的备份.请参阅下面的 javadoc:

Though what is the purpose here, if you do any changes in Set that will also reflect in Map as set returned by Map.entrySet is backup by Map. See javadoc below:

设置> java.util.Map.entrySet()

Set<Entry<Integer, String>> java.util.Map.entrySet()

返回此映射中包含的映射的 Set 视图.套装是由地图支持,因此对地图的更改会反映在集合中,并且反之亦然.如果在对集合进行迭代时修改了地图进行中(除非通过迭代器自己的删除操作,或通过对返回的映射条目的 setValue 操作iterator) 迭代的结果是未定义的.该套装支持元素移除,即从地图中移除对应的映射,通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear操作.它不支持 add 或 addAll 操作.

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. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

这篇关于转换集合&lt;Map.Entry&lt;K,V&gt;&gt;到HashMap&lt;K,V&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:转换集合&lt;Map.Entry&lt;K,V&gt;&gt;到HashMap&lt;K,V&gt;

基础教程推荐