如何将Map<key,value>转换为List<value>?我应该遍历所有映射值并将其插入列表吗?
当前回答
下面是从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;
}
其他回答
// 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是map的实例
map.values()将返回一个包含所有map值的Collection。map.keySet()将返回一个包含贴图所有键的Set。
使用Java 8 Streams API。
List<Value> values = map.values().stream().collect(Collectors.toList());
下面是从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;
}
public List<Object> convertMapToList(Map<Object, Object> map){
return new ArrayList<>(map.values());
}