Sorting User Defined Collection Using Comparator

public class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", age=" + age + '}';
    }
}

 

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;


/**
 *
 * @author Shailesh Sonare
 */
public class MyCollections {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(0, 5);
        list.add(1, 2);
        list.add(2, 3);
        list.add(3, 8);
        
        Collections.sort(list, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }            
        });
        
        for(Iterator i = list.iterator(); i.hasNext();) {
            System.out.println("" + i.next());
        }
        
        
        Hashtable ht = new Hashtable();
        ht.put(0, "Shailesh Sonare");
        
        HashMap hm = new HashMap();
        hm.put(0, "Mahesh Sonare");
        
        ArrayList<Student> sl = new ArrayList<Student>();
        
        sl.add(new Student("Shailesh", 28));
        sl.add(new Student("Mahesh", 20));
        sl.add(new Student("Shilpa", 22));
        
        Collections.sort(sl, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.age > o2.age) {
                    return 1;
                } else if(o1.age < o2.age) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        
        for(Iterator i = sl.iterator(); i.hasNext();) {
            System.out.println((Student)i.next());
        }
        
    }
    
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *