0
 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.

3
  • Use Collections.sort Commented Feb 11, 2013 at 4:48
  • @RohitJain thanks for reply but based on which object of map it will be sorted id or value of map.? Commented Feb 11, 2013 at 4:50
  • Search for id key, and get it's value. Commented Feb 11, 2013 at 4:52

3 Answers 3

4

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

Comments

1

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")));

Comments

0

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.

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.