HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); List list = new ArrayList(map.values()); for (String s : list) { System.out.println(s); }
假设你有:
HashMap map; // Assigned or populated somehow.
有关值的列表:
List values = new ArrayList(map.values());
有关键的列表:
List keys = new ArrayList(map.keySet());
请注意,键和值的顺序对于HashMap来说是不可靠的; 如果需要在各自的列表中保留键和值位置的一对一对应关系,请使用LinkedHashMap 。
基本上你不应该把问题的答案弄乱,因为这是令人困惑的。
然后你可以指定什么转换的意思,并select一个解决scheme
List keyList = Collections.list(Collections.enumeration(map.keySet())); List valueList = Collections.list(Collections.enumeration(map.values()));
集合接口有3个视图
中的keySet
值
的entrySet
其他已经回答将Hashmap转换成两个键和值的列表。 它完全正确
我的补充:如何将“键值对”(又名entrySet)转换成列表。
Map m=new HashMap(); m.put(3, "dev2"); m.put(4, "dev3"); List entryList = new ArrayList(m.entrySet()); for (Entry s : entryList) { System.out.println(s); }
ArrayList有这个构造函数。
使用Java 8和Stream Api的解决scheme:
private static List createListFromMapEntries (Map map){ return map.values().stream().collect(Collectors.toList()); }
用法:
public static void main (String[] args) { Map map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); List result = createListFromMapEntries(map); result.forEach(System.out :: println); }
如果你只想要迭代你的HashMap,不需要列表:
HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); for (String s : map.values()) { System.out.println(s); }
当然,如果你想在结构上修改你的映射(即不仅仅是改变现有键的值),那么你最好使用“copy to ArrayList”方法,否则你会得到一个ConcurrentModificationExceptionexception。 或者作为一个数组导出:
HashMap map = new HashMap(); map.put (1, "Mark"); map.put (2, "Tarryn"); for (String s : map.values().toArray(new String[]{})) { System.out.println(s); }
如果您想在列表中保持相同的顺序,请说:您的地图看起来像:
map.put(1, "msg1") map.put(2, "msg2") map.put(3, "msg3")
你希望你的列表看起来像
["msg1", "msg2", "msg3"] // same order as the map
你将不得不遍历Map:
// sort your map based on key, otherwise you will get IndexOutofBoundException Map treeMap = new TreeMap(map) List list = new List(); for (treeMap.Entry entry : treeMap.entrySet()) { list.add(entry.getKey(), entry.getValue()); }