如何在Java中将HashMap转换为List?

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)

  • 基本上,HashMap类的.values()方法返回值的Collection.你也可以使用.keys().ArrayList()类接受Collection作为其构造函数之一.因此,您可以从HashMap值的Collection中创建一个新的ArrayList.我不知道性能如何,但对我来说简单是值得的! (2认同)

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.

  • +1注意正确的排序应该使用 `LinkedHashMap` &lt;=&gt; `List`。此外,对于无序转换,使用 `HashMap` &lt;=&gt; `Set` 来指示它是无序的可能是一个很好的做法。 (2认同)

Dam*_*ash 7

基本上你不应该把问题弄得一塌糊涂,因为它令人困惑.

然后你可以指定转换平均值并选择其中一个解决方案

List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));

List<String> valueList = Collections.list(Collections.enumeration(map.values()));
Run Code Online (Sandbox Code Playgroud)


Vde*_*deX 7

Collection Interface有3个视图

  • 中的keySet
  • 的entrySet

其他人已回答将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有这个构造函数.


Ric*_*rdK 6

使用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)