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>() {

			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));


The above will print the names sorted ignoring the case of the first letter:

[Anna, diana, James]


So empty here ... leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.