Convert Setlt;Map.Entrylt;K, Vgt;gt; to HashMaplt;K, Vgt;(转换集合lt;Map.Entrylt;K,Vgt;gt;到HashMaplt;K,Vgt;)
问题描述
在我的代码中,我从地图创建了一个 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?
推荐答案
HashSet
和HashMap
之间没有直接转换的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.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:
设置
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.
这篇关于转换集合<Map.Entry<K,V>>到HashMap<K,V>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:转换集合<Map.Entry<K,V>>到HashMap<K,V>


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01