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

后端 未结 7 1146
春和景丽
春和景丽 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:22

    If you wanna maintain the same order in your list, say: your Map looks like:

    map.put(1, "msg1")
    map.put(2, "msg2")
    map.put(3, "msg3")
    

    and you want your list looks like

    ["msg1", "msg2", "msg3"]   // same order as the map
    

    you will have to iterate through the 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());
    }  
    

提交回复
热议问题