0

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?

4
  • 1
    Your list contains only one element. And that element is a hashmap with one name and one mark, because you overwrote them for each new student. Did you mean to create multiple hashmaps? Commented Apr 26, 2021 at 14:29
  • 1
    And your map contains only 2 entries: name and mark Commented Apr 26, 2021 at 14:31
  • if the ArrayList is appended in a loop, how will i get it ? Commented Apr 26, 2021 at 14:41
  • Read the docs: Map, especially Map.computeIfAbsent Commented Apr 26, 2021 at 14:53

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.