如何将Map<key,value>转换为List<value>?我应该遍历所有映射值并将其插入列表吗?
当前回答
列出了什么?
假设map是map的实例
map.values()将返回一个包含所有map值的Collection。map.keySet()将返回一个包含贴图所有键的Set。
其他回答
List<Value> list = new ArrayList<Value>(map.values());
假设:
Map<Key,Value> map;
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获取键和值。
如果您想确保结果列表<值>中的值按照输入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,以获取多样性)。
列出了什么?
假设map是map的实例
map.values()将返回一个包含所有map值的Collection。map.keySet()将返回一个包含贴图所有键的Set。