This question already has an answer here:
I wanted to sort an array list of objects based on one of the properties of object lets say here in my code 'name' , I searched and found out about using 'Comparator' for this option, the below class is my objects :
public class PhoneBook{
long number;
String name;
String family;
String address;
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
and I override the 'compare' method in my sort method, like this:
public void sort()
{
Collections.sort(phoneBooks, new Comparator<PhoneBook>() {
@Override
public int compare(PhoneBook o1, PhoneBook o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
}
but my problem is that I get confused why without implementing 'Comparable' in the first code like this:
public class PhoneBook implements Comparable<PhoneBook>
the sort method work well, and actually I tried the above code and it gave me error so I remove the implement part but I saw it works.
Comparable :
Comparator :
Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.
Comparator doesn't affect the original class i.e. actual class is not modified.
Comparator provides compare() method to sort elements.
We can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.
There are two ways you can do what you wanted here - one is using a custom Comperator
(as you did above), and the second is by implementing Comperable
interface.
You don't need to do both.
The first way (comparator) - you run the sort method with your comparator, and the sort method will use it in order to compare the objects. since it uses the comparator, it does not need you to implement compareTo
and Comparable
The second way (comperable) - you run the sort method without any comperator. what happens here is that the sort method will compare your object using the compareTo
method from Comperable
interface that you implement in your object
Either way will work, but you don't need both
There are two Collections.sort()
methods.
First receives only a Collection
to sort and uses the compareTo
method. In this case your class needs to implement Comparable
.
The other one which you have used receives two arguments, first is Collection
second one is the Comparator
. This one doesn't care if your class implements Comparable<? super YourClass>
as it uses provided Comparator
.
Lambda come in handy when implementing functional interfaces:
Collections.sort(phoneBooks, (o1, o2)-> o1.getName().compareToIgnoreCase(o2.getName()));