Sort the List of Objects using Comparator

Comparator is used to sort the list the Objects according to the user own logic

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


public class Example  {

    public static void main(String[] args){
        List<Student> studentList = new ArrayList<Student>();
        Student st = new Student();
        st.setsName("DEF");
        Student st1 = new Student();
        st1.setsName("ABC");
        studentList.add(st);
        studentList.add(st1);   
        Collections.sort(studentList,new Comparator<Student>(){
              public int compare(Student st, Student st1) {
                    return st.getsName().compareToIgnoreCase(st1.getsName());
                  }
                });
       
        for(Student stud: studentList){
            System.out.println(stud.getsName());
           
        }
       
    }
}

O/P for the above program is :

ABC
DEF

0 Response to "Sort the List of Objects using Comparator"

Post a Comment