Similar to reversing elements in array this example will show how to sort an array of objects based on a specified comparator using java, guava and apache commons. Each code snippet contains an array of years in which the University of Wisconsin football team won a conference title that will be sorted in natural order, descending, ascending and reverse order.
Straight up Java
Sort numeric array
Using java, this snippet will sort an array in ascending numerical order with Arrays.sort.
Sort numeric array decending
Using java, this snippet will sort a numeric array in decending order using the overloaded Arrays.sort. The first parameter is the array and the second is the comparator. We will use Collections.reverseOrder comparator which will impose the reverse natural order.
Sort string array
Similar to the sort numeric array above, this snippet will sort a string array using Arrays.sort.
Java 8
Sort numeric array
By using the specialized IntStream in java 8, we will first create a stream by calling IntStream.of. By calling the sort method next we will return a stream in sort order and then convert it to an array by calling toArray. IntStream has two sister streams, double stream and long stream if you dealing with primitive double and long respectively.
Sort numeric array decending
Like the sort numeric array decending example above, we will create a comparator with a lambda expression, then a reversed comparator and call Arrays.sort passing in the array and the reversed comparator.
Sort string array
Using the Arrays.stream().sorted() we will sort the array according to the natural order of the elements.
Sort string array by length
By using a lambda expresison, we will abstract specific details of how to sort and focus on creating a simple comparator comparing the strings length.