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>
 */
public class ListMapStringObjectSorting {


  public static void main(String[] args) {

 
    Map map1 = new HashMap();
    map1.put("name", "Y");
    map1.put("num", 1);

      Map map2 = new HashMap();

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

      Collections.sort(mapList, new Comparator> () {

        public int compare(Map m1, Map 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>() {
        public int compare(final Map o1, final Map 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> :

    
for (Map map : mapList) {
        for (Map.Entry entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(key + " = " + value);
        }

   }

No comments: