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>
基础教程推荐
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01