Sort array

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.

@Test
public void sort_numeric_array_in_java () {

    int[] uwConferenceTitles = {
            1896, 2011, 1901, 1912, 1952,
            1959, 1962, 1999, 1897, 1906,
            1993, 1998,  2010,  2012};

    Arrays.sort(uwConferenceTitles);

    logger.info(Arrays.toString(uwConferenceTitles));

    assertArrayEquals(new int[] {
            1896, 1897, 1901, 1906, 1912,
            1952, 1959, 1962, 1993, 1998,
            1999, 2010, 2011, 2012},
            uwConferenceTitles);
}

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.

@Test
public void sort_numeric_array_decending_in_java () {

    Integer[] uwConferenceTitles = {
            1896, 2011, 1901, 1912, 1952,
            1959, 1962, 1999, 1897, 1906,
            1993, 1998,  2010,  2012};

    Arrays.sort(uwConferenceTitles, Collections.reverseOrder());

    logger.info(Arrays.toString(uwConferenceTitles));

    assertArrayEquals(new Integer[] {
            2012, 2011, 2010, 1999, 1998,
            1993, 1962, 1959, 1952, 1912,
            1906, 1901, 1897, 1896},
            uwConferenceTitles);

}

Sort string array

Similar to the sort numeric array above, this snippet will sort a string array using Arrays.sort.

@Test
public void sort_string_array_in_java () {

    String[] wiStateParks = {
            "Mill Bluff State Park",
            "Amnicon Falls State Park",
            "Wyalusing State Park",
            "Big Foot Beach State Park",
            "Willow River State Park",
            "Roche-A-Cri State Park"
        };

    Arrays.sort(wiStateParks);

    logger.info(Arrays.toString(wiStateParks));

    assertArrayEquals(new String[] {
            "Amnicon Falls State Park",
            "Big Foot Beach State Park",
            "Mill Bluff State Park",
            "Roche-A-Cri State Park",
            "Willow River State Park",
            "Wyalusing State Park"},
            wiStateParks);

}

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.

@Test
public void sort_numeric_array_in_java8() {

    int[] uwConferenceTitles = { 1896, 2011, 1901, 1912, 1952, 1959, 1962,
            1999, 1897, 1906, 1993, 1998, 2010, 2012 };

    int[] sortedTitles = IntStream.of(uwConferenceTitles).sorted()
            .toArray();

    logger.info(Arrays.toString(uwConferenceTitles));

    assertArrayEquals(new int[] { 1896, 1897, 1901, 1906, 1912, 1952, 1959,
            1962, 1993, 1998, 1999, 2010, 2011, 2012 }, sortedTitles);
}

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.

@Test
public void sort_numeric_array_decending_in_java8 () {

    Integer[] uwConferenceTitles = {
            1896, 2011, 1901, 1912, 1952,
            1959, 1962, 1999, 1897, 1906,
            1993, 1998,  2010,  2012};

    Comparator<Integer> normal = Integer::compare;
    Comparator<Integer> reversed = normal.reversed();

    Arrays.sort(uwConferenceTitles, reversed);

    assertArrayEquals(new Integer[] {
            2012, 2011, 2010, 1999, 1998,
            1993, 1962, 1959, 1952, 1912,
            1906, 1901, 1897, 1896},
            uwConferenceTitles);
}

Sort string array

Using the Arrays.stream().sorted() we will sort the array according to the natural order of the elements.

@Test
public void sort_string_array_in_java8 () {

    String[] wiStateParks = {
            "Mill Bluff State Park",
            "Amnicon Falls State Park",
            "Wyalusing State Park",
            "Big Foot Beach State Park",
            "Willow River State Park",
            "Roche-A-Cri State Park"
        };

    Object[] sorted = Arrays.stream(wiStateParks).sorted().toArray();

    logger.info(Arrays.toString(sorted));

    assertArrayEquals(new String[] {
            "Amnicon Falls State Park",
            "Big Foot Beach State Park",
            "Mill Bluff State Park",
            "Roche-A-Cri State Park",
            "Willow River State Park",
            "Wyalusing State Park"},
            sorted);

}

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.

@Test
public void sort_string_array_in_java8_by_length () {

    String[] wiStateParks = {
            "Mill Bluff State Park",
            "Amnicon Falls State Park",
            "Wyalusing State Park",
            "Big Foot Beach State Park",
            "Willow River State Park",
            "Roche-A-Cri State Park"
        };

    Arrays.sort(wiStateParks, (s1, s2) -> s1.length() - s2.length());

    logger.info(Arrays.toString(wiStateParks));

    //or Arrays.sort(wiStateParks, (String s1, String s2) -> s1.length() - s2.length());

    assertArrayEquals(new String[] { "Wyalusing State Park",
            "Mill Bluff State Park", "Roche-A-Cri State Park",
            "Willow River State Park", "Amnicon Falls State Park",
            "Big Foot Beach State Park" }, wiStateParks);
}

Google Guava

Ordering is a guava "enriched" comparator class which gives the flexibility to create, chain and apply while ordering arrays.

Sort numeric array decending

@Test
public void sort_numeric_array_decending_in_java_with_guava () {

    Integer[] uwConferenceTitles = {
            1896, 2011, 1901, 1912, 1952,
            1959, 1962, 1999, 1897, 1906,
            1993, 1998,  2010,  2012};

    Arrays.sort(uwConferenceTitles, Ordering.natural().reverse());

    logger.info(Arrays.toString(uwConferenceTitles));

    assertArrayEquals(new Integer[] {
            2012, 2011, 2010, 1999, 1998,
            1993, 1962, 1959, 1952, 1912,
            1906, 1901, 1897, 1896},
            uwConferenceTitles);

}

Sort string array by length


@Test
public void sort_string_array_in_java_with_guava_by_length () {


    Ordering<String> byLengthOrdering = new Ordering<String>() {
        public int compare(String left, String right) {
            return Ints.compare(left.length(), right.length());
        }
    };

    String[] wiStateParks = { "Mill Bluff State Park",
            "Amnicon Falls State Park", "Wyalusing State Park",
            "Big Foot Beach State Park", "Willow River State Park",
            "Roche-A-Cri State Park" };

    Arrays.sort(wiStateParks, byLengthOrdering);

    logger.info(Arrays.toString(wiStateParks));

    assertArrayEquals(new String[] { "Wyalusing State Park",
            "Mill Bluff State Park", "Roche-A-Cri State Park",
            "Willow River State Park", "Amnicon Falls State Park",
            "Big Foot Beach State Park" }, wiStateParks);

}