转换集< Map.Entry< K,V>>到HashMap< K,V> [英] Convert Set<Map.Entry<K, V>> to HashMap<K, V>

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

问题描述

在我的代码中,我从地图中创建了一个 Set< Map.Entry< K,V> 。现在我想重新创建相同的地图表单,所以我想将 HashSet< Map.Entry< K,V> 转换回 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?

推荐答案

p>在java中没有内置的API,用于在 HashSet HashMap 之间进行直接转换,您需要遍历set和使用 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.entrySet Map 备份。请参阅 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.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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆