How does one convert a HashMap to a List in Java?

后端 未结 7 1162
春和景丽
春和景丽 2020-12-08 01:35

In Java, how does one get the values of a HashMap returned as a List?

7条回答
  •  我在风中等你
    2020-12-08 02:21

    Assuming you have:

    HashMap map; // Assigned or populated somehow.
    

    For a list of values:

    List values = new ArrayList(map.values());
    

    For a list of keys:

    List keys = new ArrayList(map.keySet());
    

    Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.

提交回复
热议问题