Tag - Lambda

Java 8 Lambda: Comparator example

In this example, we will show you how to use Java 8 Lambda expression to write a Comparator to sort a List. 1. Classic Comparator example. Comparator<Developer> byName = new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getName().compareTo(o2.getName()); } }; 2. Lambda expression equivalent. Comparator<Developer> byName = (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName()); 1. Sort without Lambda Example to compare the Developer objects using their age. Normally, you use Collections.sort and pass an anonymous Comparator class like this :TestSorting.java package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TestSorting { public static...

Read more...