如何将Map<key,value>转换为List<value>?我应该遍历所有映射值并将其插入列表吗?
当前回答
map.entrySet()提供了一个包含键和值的map.Entry对象集合。然后,您可以将其转换为任何您喜欢的集合对象,例如newArrayList(map.entrySet());
其他回答
如果需要值的不可变副本:
List<Value> list = List.copyOf(map.values())
下面是从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;
}
列出了什么?
假设map是map的实例
map.values()将返回一个包含所有map值的Collection。map.keySet()将返回一个包含贴图所有键的Set。
如果您想确保结果列表<值>中的值按照输入Map<键,值>的键顺序,则需要以某种方式“通过”SortedMap。
要么从具体的SortedMap实现(如TreeMap)开始,要么在将输入Map转换为List之前将其插入SortedMap。例如。:
Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));
否则,您将获得Map实现提供的任何本机排序,这通常可以是自然键排序以外的其他排序(请尝试Hashtable或ConcurrentHashMap,以获取多样性)。
// 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());
}