Java Comparator comparingInt() Method
Example
Sort a list of cars by year:
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
static class Car {
String brand;
int year;
Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
public String toString() {
return brand + " " + year;
}
}
public static void main(String[] args) {
ArrayList<Car> myCars = new ArrayList<Car>();
myCars.add(new Car("BMW", 1999));
myCars.add(new Car("Honda", 2006));
myCars.add(new Car("Ford", 1970));
myCars.sort(Comparator.comparingInt(c -> c.year));
System.out.println(myCars);
}
}
Definition and Usage
The comparingInt() method creates a comparator that sorts objects by an int value, for example the year of a car. The numbers are sorted from small to large.
It works like comparing(), but the key is an int, so Java does not need to turn each number into an Integer object first.
Tip: For long and double values, use comparingLong() and comparingDouble(). They work the same way.
Syntax
public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
T refers to the data type of the objects to sort, for example Car.
Parameter Values
| Parameter | Description |
|---|---|
| keyExtractor | Required. A ToIntFunction or lambda expression that takes an object and returns the int value to sort by, for example c -> c.year. |
Technical Details
| Returns: | A Comparator that compares objects by the int value. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods