简体   繁体   中英

sort arraylist with key ascending

map = new LinkedHashMap<String, String>(); 
list = new ArrayList<HashMap<String, String>>(); 

map.put("id", id);
map.put("amt", amt);

list.add(map);

How to sort the list with ascending order of amt . I was unable to do this. I'd really appreciate any help.

I am adding id , amt in loop. How to sort with key as amt ?

id=1,2,3,4,5
amt=1000,33333,77,9087,5432

Simply use TreeMap :

Map<String, String> map = new TreeMap<String, String>();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();

map.put("id", "id");
map.put("amd", "amd");

list.add(map);

System.out.println(list);

Output:

[{amd=amd, id=id}]

Now if the Id is in upper case and amd in lower case then you should to override the default behavior of TreeMap using Comparator in the constructor (to ensure that the sorting for strings keys is correct):

Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.toLowerCase().compareTo(o2.toLowerCase());
        }
    });

Look to the TreeMap API Documentation

Your question is not very clear as at some point you seem to mention sorting a list with only one element (your map). But I assume you want to sort the keys in that map (either inside the map or after adding them all to some list).

However, for sorting lists you have Collections.sort() which can rely on both natural order (if elements implement Comparable ) or a custom Comparator . Also, you can have a look at SortedSet (and the TreeSet implementation) if you want to have the order maintained while you add/remove elements.

For maintaining a map with ordered keys, you have the SortMap (with a notable implementation: TreeMap ) which will make sure the order it preserved at any moment -- you can add the elements randomly and whenever you iterate you'll get the keys in order. Again the order will can be the natural one (provided by Comparable.compareTo ) or you can provide custom ordering by implementing the Comparator interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM