In Java 8 and later, you can use lambda expressions to create instances of the java.util.Comparator
functional interface, which represents a comparison function that compares two objects of the same type and returns an int
value indicating their relative order.
To create a Comparator
using a lambda expression, you can use the following syntax:
Comparator<Type> comparator = (a, b) -> { // code to compare a and b return result; };
Here, Type
is the type of the objects being compared, a
and b
are the objects being compared, and result
is the result of the comparison.
Here is an example of how you can use a lambda expression to create a Comparator
that compares Person
objects by their age:
import java.util.Comparator; public class MyClass { public static void main(String[] args) { Comparator<Person> comparator = (a, b) -> a.getAge() - b.getAge(); int result = comparator.compare(new Person("Alice", 25), new Person("Bob", 30)); System.out.println(result); // Outputs -5 } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }