Comparator

 It is an interface, Comparator is used over Comparable when the source code is not available and we can have an option of proving the own sorting logic.

The class which is implementing the Comparator interface should override the  compare(Object o1, Object o2) method.

Late we need to create the object of the class which is implementing the comparator interface.

and that object should be passed to the Collections.sort(x1, obj) method.

we can also use the lambda implementation as we are override only one method and it is a functional interface.


import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;


class ComparatorImpl implements Comparator<Student>{



@Override

public int compare(Student s1, Student s2) {

// TODO Auto-generated method stub

return s1.name.compareTo(s2.name);

}

}


public class ComparatorExample {


public static void main(String[] args) {

// TODO Auto-generated method stub


ArrayList<Student> al=new ArrayList<Student>();

al.add(new Student(21,"Vishnu","java"));

al.add(new Student(30,"Aswini","js"));

al.add(new Student(28,"Chandu","python"));

Comparator com = new ComparatorImpl();

Collections.sort(al,com);

System.out.println(al);

}


}


Comments

Popular posts from this blog

Advantages and Disadvantages of Monolithic Architecture

Monolithic Architecture

Eclipse debugging