如何将Map<key,value>转换为List<value>?我应该遍历所有映射值并将其插入列表吗?
当前回答
如果需要值的不可变副本:
List<Value> list = List.copyOf(map.values())
其他回答
public List<Object> convertMapToList(Map<Object, Object> map){
return new ArrayList<>(map.values());
}
我猜你想将地图中包含的值转换为列表?最简单的方法是调用Map接口的values()方法。这将返回Map中包含的值对象的集合。
请注意,此集合由Map对象支持,对Map对象的任何更改都将反映在此处。因此,如果您希望一个单独的副本不绑定到Map对象,只需创建一个新的List对象,如ArrayList,传递值Collection,如下所示。
ArrayList<String> list = new ArrayList<String>(map.values());
// you can use this
List<Value> list = new ArrayList<Value>(map.values());
// or you may use
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());
}
Map<String, String > map = new HapshMap<String, String>;
map.add("one","java");
map.add("two", "spring");
Set<Entry<String, String>> set = map.entrySet();
List<Entry<String, String>> list = new ArrayList<Entry<String, String>> (set);
for(Entry<String, String> entry : list) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("java", 20);
map.put("C++", 45);
Set <Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
我们可以在列表中同时使用键和值对。也可以通过迭代列表使用Map.Entry获取键和值。