简体   繁体   中英

How to sort a HashMap with key,value pair from an ArrayList in Java

Hi i have a ArrayList of HashMap and i need the HashMap to be sorted by its key,Value.

ArrayList<HashMap> newList = new ArrayList();

loop start:

HashMap hashData = new HashMap();

hashData.put("name", "string-studentname");
hashData.put("mark", "int-studentmark");

newList.add(hashData);

loop end:

I need the newList to be sorted by the key-mark.

How do i get it?

If you have multiple entries in your ArrayList and the key is the same, you can just sort via:

newList.sort(Comparator.comparingInt(o -> o.get("mark")));

Assuming you're typing the map properly:

HashMap<String, Integer> hashData = new HashMap<>();
hashData.put("mark", 1);

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