如何将Map<key,value>转换为List<value>?我应该遍历所有映射值并将其插入列表吗?
当前回答
map.entrySet()提供了一个包含键和值的map.Entry对象集合。然后,您可以将其转换为任何您喜欢的集合对象,例如newArrayList(map.entrySet());
其他回答
List<Value> list = new ArrayList<Value>(map.values());
假设:
Map<Key,Value> map;
列出了什么?
假设map是map的实例
map.values()将返回一个包含所有map值的Collection。map.keySet()将返回一个包含贴图所有键的Set。
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中获取值的通用方法。
public static <T> List<T> ValueListFromMap(HashMap<String, T> map) {
List<T> thingList = new ArrayList<>();
for (Map.Entry<String, T> entry : map.entrySet()) {
thingList.add(entry.getValue());
}
return thingList;
}
如果需要值的不可变副本:
List<Value> list = List.copyOf(map.values())