Rakesh KR


Sort a list in Java8 (Lambda Expression)

We can easily sort a list in Java 8


List names = Arrays.asList("Rakesh", "Amal", "Ramez", "Sreejith");
System.out.println("List Before Sort :");
names.forEach(name -> System.out.println(name));
Collections.sort(names, (a, b) -> a.compareTo(b));
System.out.println("List After Sort  :");
names.forEach(System.out::println);

In previous version of Java we sorted the list as,


List names = Arrays.asList("Rakesh", "Amal", "Ramez", "Sreejith");
Collections.sort(names, new Comparator() {
    @Override
    public int compare(String a, String b) {
        return b.compareTo(a);
    }
});

The static utility method Collections.sort accepts a list and a comparator in order to sort the elements of the given list.

Java 8 comes with a much shorter syntax, lambda expressions:


Collections.sort(names, (String a, String b) -> {
    return b.compareTo(a);
});

Continue reading →