Arrays.sort(arr);Arrays.sort(arr, fromIndex, toIndex);// reverse sorting example// since custom Comparator not supportedprivate void reverseArray(int[] arr) { int N = arr.length; int i = 0; int j = N - 1; while (i < j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; }}// Alternative: Box, reverse sort, unboxint[] reversed = Arrays.stream(arr) .boxed() .sorted(Collections.reverseOrder()) .mapToInt(Integer::intValue) .toArray();// printing arraySystem.out.println(Arrays.toString(arr));
Object Array
Arrays.sort(T[]);Arrays.sort(T[], Comparator);Arrays.sort(T[], fromIndex, toIndex, Comparator);// ExamplesArrays.sort(peopleArray); // need Person class with Comparable implementationArrays.sort(peopleArray, Comparator.comparing(Person::getName));Arrays.sort(peopleArray, 0, 4, Comparator.comparing(Person::getName));// print object array// need @ToString on Person classSystem.out.println(Arrays.toString(peopleArray));
2D Primitive Array
Since int[][] is an array of int[] which in fact is an object
Object Array sorting can be used
Arrays.sort(arr2, (a, b) -> Integer.compare(a[0], b[0]));// print nested arraysSystem.out.println(Arrays.deepToString(arr2));
// requires comparator in argumentlist.sort(Comparator);// Pass null to trigger default natural orderinglist.sort(null);
Wrapper Comparison Utilities
Integral Types
x - y can fail with extreme values
Integer.compare(int x, int y)
Long.compare(long x, long y)
Short.compare(short x, short y)
Byte.compare(byte x, byte y)
Character.compare(char x, char y)
Floating Types
x - y can fail to handle NaN and distinguish positive/negative/zero
Float.compare(float x, float y)
Double.compare(double x, double y)
Logical Type
Boolean.compare(boolean x, boolean y)
Comparable
package: java.lang
Interface: Comparable<T>
int compareTo(T o)
Return: negative (this<o), zero (this==o), positive (this>o)
Defines the natural ordering for objects of a class implementing it
String, primitive wrappers (e.g., Integer, Double), and Date/Time classes have implicit Comparable behavior defined
Any Comparator utility that does not define a custom comparison strategy implicitly relies on Comparable
class Person implements Comparable<Person> { String name; String city; @Override public int compareTo(Person o) { return this.name.compareTo(o.getName()); }}
An object that implements the Comparator interface is called a comparator
Return: negative (o1<o2), zero (o1==o2), positive (o1>o2)
Syntax
class syntax
class NameComparator implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); }}Comparator<Person> comparator = new NameComparator();
These are static factory methods of Comparator interface
These are used to start comparator chain
General Utilities
Comparator.naturalOrder()
Comparator.reverseOrder() also same as Collections.reverseOrder()
Handling nulls
Comparator.nullsFirst(Comparator)
Comparator.nullsLast(Comparator)
Custom Mapping
Comparator.comparing(Function)
Comparator.comparing(Function, Comparator)
Comparator.comparingInt(ToIntFunction)
Comparator.comparingLong(ToLongFunction)
Comparator.comparingDouble(ToDoubleFunction)
For primitives use specialized classes
// Avoid: int primitive age is boxed internallylist.stream() .sorted(Comparator.comparing(p -> p.getAge())) .forEach(System.out::println);// Prefer: Directly compares raw int primitive agelist.stream() .sorted(Comparator.comparingInt(Person::getAge)) .forEach(System.out::println);
Instance Methods
These are instance methods of Comparator
defined as default methods of Comparator interface
These can be used to chain after static factory methods or another object methods
// assumes one of the person is null in listlist.stream() .sorted(Comparator.nullsFirst(Comparator.comparing(Person::getCity))) .forEach(System.out::println);
Sorting with null properties
// assumes one of the person is null in list// and person.getCity() is null for some objectlist.stream() .sorted(Comparator.nullsFirst( // null-safe Comparator.comparing( Person::getCity, Comparator.nullsFirst(Comparator.naturalOrder()) // null-safe ) )) .forEach(System.out::println);