Saturday, May 2, 2015

Sorting of ListMapStringObject using Comparator

Sorting a List using Comparator

package com.yash;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * Sort a List<Map<String,Object>>
 */
public class ListMapStringObjectSorting {


  public static void main(String[] args) {
 
   Map<String, Object> map1 = new HashMap<String, Object>();
   map1.put("name", "Y");
   map1.put("num", 1);

     Map<String, Object> map2 = new HashMap<String, Object>();
   map2.put("name", "A");
   map2.put("num", 3);
   
   Map<String, Object> map3 = new HashMap<String, Object>();
   map3.put("name", "D");
   map3.put("num", 2);
   
   Map<String, Object> map4 = new HashMap<String, Object>();
   map4.put("name", "C");
   map4.put("num", 5);
   
   List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
   mapList.add(map1);
   mapList.add(map2);
   mapList.add(map3);
   mapList.add(map4);

     Collections.sort(mapList, new Comparator<Map<String, Object>> () {
       public int compare(Map<String, Object> m1, Map<String, Object> m2) {
           return ((Integer) m1.get("num")).compareTo((Integer) m2.get("num")); //ascending order
           //return ((Integer) m2.get("num")).compareTo((Integer) m1.get("num")); //descending order
       }
   });
   //Sort by number
   //[{num=1, name=Y}, {num=2, name=D}, {num=3, name=A}, {num=5, name=C}]
   System.out.println(mapList);
   
   Collections.sort(mapList, new Comparator<Map<String, Object>>() {
       public int compare(final Map<String, Object> o1, final Map<String, Object> o2) {
           return ((String) o1.get("name")).compareTo((String) o2.get("name")); //ascending order
       }
   });
   //Sort by name
   //[{num=3, name=A}, {num=5, name=C}, {num=2, name=D}, {num=1, name=Y}]
   
   System.out.println(mapList);
}

}



Iterate a list - List<Map<String,Object>> :
   
for (Map<String, Object> map : mapList) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(key + " = " + value);
        }

   }

3 comments: