I am looking to implement a sort feature for my address book application.
I want to sort an ArrayList
. Contact
In addition to what was already posted you should know that since Java 8 we can shorten our code and write it like:
Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
or since List now have sort
method
yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
Since Java 8, functional interfaces (interfaces with only one abstract method - they can have more default or static methods) can be easily implemented using:
arguments -> body
source::method
.Since Comparator
has only one abstract method int compare(T o1, T o2)
it is functional interface.
So instead of (example from @BalusC answer)
Collections.sort(contacts, new Comparator() {
public int compare(Contact one, Contact other) {
return one.getAddress().compareTo(other.getAddress());
}
});
we can reduce this code to:
Collections.sort(contacts, (Contact one, Contact other) -> {
return one.getAddress().compareTo(other.getAddress());
});
We can simplify this (or any) lambda by skipping
{return
... }
So instead of
(Contact one, Contact other) -> {
return one.getAddress().compareTo(other.getAddress();
}
we can write
(one, other) -> one.getAddress().compareTo(other.getAddress())
Also now Comparator
has static methods like comparing(FunctionToComparableValue)
or comparing(FunctionToValue, ValueComparator)
which we could use to easily create Comparators which should compare some specific values from objects.
In other words we can rewrite above code as
Collections.sort(contacts, Comparator.comparing(Contact::getAddress));
//assuming that Address implements Comparable (provides default order).