Integer.compare()
Compares two int values: negative means x is smaller, 0 means equal, positive means x is larger.
Available since: Java 7
Syntax
public static int compare(int x, int y)Parameters
| Parameter | Type | Description |
|---|---|---|
| x | int | The first number. |
| y | int | The second number. |
Return value
int-1, 0 or 1.
Examples
The three possible results:
void main() {
IO.println(Integer.compare(3, 7));
IO.println(Integer.compare(7, 3));
IO.println(Integer.compare(5, 5));
}Output:
-1
1
0A comparator for sorting by age:
record Person(String name, int age) {}
void main() {
List<Person> people = new ArrayList<>(List.of(
new Person("Anna", 30), new Person("Oleg", 25), new Person("Mia", 41)));
people.sort((a, b) -> Integer.compare(a.age(), b.age()));
IO.println(people);
}Output:
[Person[name=Oleg, age=25], Person[name=Anna, age=30], Person[name=Mia, age=41]]Why not a - b: subtraction overflows and gives the wrong sign:
void main() {
int a = Integer.MIN_VALUE;
int b = 1;
IO.println(a - b);
IO.println(Integer.compare(a, b));
}Output:
2147483647
-1Notes
Long, Double, Short, Byte and Character have the same methods. Double.compare() handles NaN and -0.0 correctly, which the < and > operators do not. For sorting objects Comparator.comparingInt(Person::age) is shorter.
See also
- Comparator.comparing() — Creates a comparator that compares objects by one key.
- Comparable.compareTo() — Defines the natural order of a class — used by sort() and TreeSet.
- List.sort() — Sorts a list in place using a given rule.
- Integer.MAX_VALUE — The largest int value; its partner is Integer.MIN_VALUE.
In the tutorial
- Wrapper classes — Integer, Double, Boolean and Character in Java: autoboxing and unboxing, null instead of a number, the Integer cache and why wrappers must not be compared with ==.