How sort an ArrayList of HashMaps holding several key-value pairs each?

前端 未结 3 1196
旧巷少年郎
旧巷少年郎 2020-12-05 03:13

I need to call an external API with an ArrayList of HashMaps holding several predefined key-value pairs each. An example:

ArrayList

        
3条回答
  •  囚心锁ツ
    2020-12-05 04:15

    (This is not an answer to the asked question - Jon did this already -, but the comment field is too small for this.)

    Your data structure looks like you misunderstood the key-value structure of maps (and Hash maps in your example).

    A Map can contain any number of keys, and for each key also a value. A pair of key and value is given by a Map.Entry (which can be obtained by the entrySet() method of the map). If you then want to sort by key, simply use a SortedMap (like TreeMap) instead of the usual HashMap.

    You are emulating the individual entries by a HashMap each, then putting them all in a ArrayList ... :-/

    Here what I would have done in your example:

    Map map = new TreeMap();
    map.put("B key", "B value");
    map.put("A key", "B value");
    
    System.out.println(map); // already sorted
    

提交回复
热议问题