Use Lambdas Instead of Anonymous Classes In Java
Another useful feature introduced since Java 8 is the possibility to use lambdas instead of anonymous classes. Here is an example:
Imagine you have the following list of names:
List<String> names = Arrays.asList("James", "diana", "Anna");
If you want to sort it alphabetically ignoring the case, you would have to use a Comparator and implement its compare method in an anonymous class like this:
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareToIgnoreCase(o2);
}
});
You can accomplish exactly the same with a lambda in a much more concise way:
Collections.sort(names, (a, b) -> a.compareToIgnoreCase(b));
The complete test class will look like this:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> names = Arrays.asList("James", "diana", "Anna");
Collections.sort(names, (a, b) -> a.compareToIgnoreCase(b));
System.out.println(names);
}
}
The above will print the names sorted ignoring the case of the first letter:
[Anna, diana, James]