Showing posts with label sort arraylist. Show all posts
Showing posts with label sort arraylist. Show all posts

Wednesday, October 30, 2013

Sort an ArrayList base on multiple attributes using java/grails

I have an ArrayList of object. The object contain attributes name and classValue. So I want to sort the objects on the classValue, and for all objects in the same classValue I want to sort them on name.


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

/**
 *
 * @author Pritom Kumar
 */
public class MapSort {
    public static void main(String[] args) {
        MapSort mapSort = new MapSort();
        mapSort.sort();
    }
    
    public void sort() {
        List keys = new ArrayList();
        HashMap map1 = new HashMap();
        map1.put("name", "Pritom");
        map1.put("classValue", 5);
        keys.add(map1);
        
        HashMap map2 = new HashMap();
        map2.put("name", "Bappi Lahiri");
        map2.put("classValue", 10);
        keys.add(map2);
        
        HashMap map3 = new HashMap();
        map3.put("name", "Ashok Kumar");
        map3.put("classValue", 5);
        keys.add(map3);

        Collections.sort(keys,
            new Comparator() {
                public int compare(Object left, Object right) {
                    HashMap leftMap = (HashMap) left;
                    HashMap rightMap = (HashMap) right;
                    Integer classValue1 = Integer.parseInt(leftMap.get("classValue").toString());
                    Integer classValue2 = Integer.parseInt(rightMap.get("classValue").toString());
                    int comp = classValue1.compareTo(classValue2);
                    return comp == 0 ? leftMap.get("name").toString().compareTo(rightMap.get("name").toString()) : comp;
                }
            });

        //List the values
        Object[] keyList = keys.toArray();
        for(Integer index = 0; index < keyList.length; index++) {
            System.out.println(keyList[index]);
        }
    }
}


And the output is as following. At first sorts by classValue and then by name.

{name=Ashok Kumar, classValue=5}
{name=Pritom, classValue=5}
{name=Bappi Lahiri, classValue=10}