In Java, the Comparator class is used
for sorting collections. In the following examples, we will sort a list of
players based on name, surname, name length and last name letter. We will first
sort them as we did before, using anonymous inner classes, and then reduce our
code using lambda expressions.
In the first example, we will sort our
list by name. Using the old way, this looks like this:
String[] players = {"Avijit", "Chintu", "Akshay", "Santosh", "Ritesh", "Avisek", "Krushna", "Surya", "Rudra", "Biswajit"};
// Sort players by name using anonymous innerclass
Arrays.sort(players, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return (s1.compareTo(s2));
}
});
With lambdas, the same thing can be achieved like this:
// Sort players by name using lambda expression
Comparator<String> sortByName = (String s1, String s2) -> (s1.compareTo(s2));
Arrays.sort(players, sortByName);
// or this
Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));