sunleo
sunleo

Reputation: 10947

How to sort map inside of List in java

 List<Map<String,String>> consolidErr = new LinkedList<Map<String,String>>();

 Map m1= new HashMap<String,String>();
 m1.put("id","1");
 m1.put("value","value1");

 Map m2= new HashMap<String,String>();
 m2.put("id","2");
 m2.put("value","value2");

 Map m3= new HashMap<String,String>();
 m3.put("id","3");
 m3.put("value","value3");

add all m1,m3 and m2 in list

then sort maps based on ids in map now i want maps in list as m1,m2 and m3.

Now I want to sort based on the ids in the map, I did that using iteration of list and keep first id of map as checker and compare with next it works if there any other better way than that using built-in methods.?Please give your ideas.am using bubble sort for this now.

Upvotes: 0

Views: 233

Answers (3)

sparker
sparker

Reputation: 1578

In Java 8, we can sort the list of maps in a single line.

list.sort(Comparator.comparing((Map<String,String> mp) -> mp.get("Id")));

Upvotes: 1

Olimpiu POP
Olimpiu POP

Reputation: 5067

I would use instead the PriorityQueue

as a wrapper for your list. By providing the Comparator to the constructor when creating it, would assure you that your list will remain sorted after each insertion of a new element to the list.

Upvotes: 0

Steve B.
Steve B.

Reputation: 57274

The simplest way to do this in java (or at least, with the least mess) is to use a custom comparator.

The idea is that if you have objects with a natural sort (anything that extends Comparable) you can just ask for the sorting , e.g.

Collections.sort(List<Integer> .. 

otherwise you can just pass in a Comparator that describes how you want objects compared, with any custom logic you want, e.g. (roughly - this is off the top of my head and doesn't have error checking, but should be enough to give you the idea) -

List<Map<String,String>> consolidErr = ...
enter code here
Collections.sort(consolidErr, new Comparator<Map<String,String>>(){
     public int compare(Map<String,String> a, Map<String,String> b){ 
        return a.get("id").compareTo(b.get("id"));}
    })

Upvotes: 4

Related Questions