Comparators in Java
Comparators in Java
[email protected]
A Comparator in Java is an interface that is used to order the objects of
user-defined classes. A comparator object is capable of comparing two
objects of the same class.
Method of Collections class for sorting List elements is used to sort the
elements of List by the given comparator.
public void sort(List list, ComparatorClass c)
[email protected]
1 -> obj1 is greater than obj2
It uses this result to then determine if they(obj1 & obj2) should be swapped
for their sort.
Collections.sort (list);
System.out.println (list);
}
}
/**
* This function compares 2 objects
* A person object is passed as an argument
* and returns negative integer, zero, or a positive integer
* as this object is less than, equal to, or greater than the specified object.
*/
@Override
public int compareTo(Person person){
if(this.age == person.age)
return 0;
[email protected]
else
return (this.age < person.age) ? -1 : 1;
}
@Override
public String toString(){
return this.name + ":" + this.age;
}
}
Format:
Comparator<ClassName> comparator = Comparator.comparing(o -> o.property);
Example:
Comparator<Student> comparator = Comparator.comparing(o -> o.age);
Collections.sort(students, comparator);