Spi*_*der 51 java dictionary list arraylist hashmap
在Java中,如何将HashMap返回的值作为List?
Spi*_*der 88
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
mae*_*ics 70
假设你有:
HashMap<Key, Value> map; // Assigned or populated somehow.
Run Code Online (Sandbox Code Playgroud)
对于值列表:
List<Value> values = new ArrayList<Value>(map.values());
Run Code Online (Sandbox Code Playgroud)
有关键列表:
List<Key> keys = new ArrayList<Key>(map.keySet());
Run Code Online (Sandbox Code Playgroud)
请注意,使用HashMap时,键和值的顺序将不可靠; 如果需要保持各自列表中键和值位置的一对一对应关系,请使用LinkedHashMap.
基本上你不应该把问题弄得一塌糊涂,因为它令人困惑.
然后你可以指定转换平均值并选择其中一个解决方案
List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));
List<String> valueList = Collections.list(Collections.enumeration(map.values()));
Run Code Online (Sandbox Code Playgroud)
Collection Interface有3个视图
其他人已回答将Hashmap转换为两个键和值列表.它非常正确
我的补充:如何将"键值对"(aka entrySet)转换为列表.
Map m=new HashMap();
m.put(3, "dev2");
m.put(4, "dev3");
List<Entry> entryList = new ArrayList<Entry>(m.entrySet());
for (Entry s : entryList) {
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
ArrayList有这个构造函数.
使用Java 8和Stream Api的解决方案:
private static <K, V> List<V> createListFromMapEntries (Map<K, V> map){
return map.values().stream().collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
用法:
public static void main (String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
List<String> result = createListFromMapEntries(map);
result.forEach(System.out :: println);
}
Run Code Online (Sandbox Code Playgroud)