Is list sorted

This example will determine if an arraylist is sorted not show you how to sort an arraylist. It will check if each element is greater than or equal to the element before it. Each snippet will use guava Ordering utility class calling the Ordering.isOrdered method using a list of numbers/strings in descending and case insensitive are ordered.

Google Guava

Numbers sorted

@Test
public void is_list_of_numbers_sorted_in_java_with_guava () {

    List<Integer> uwConferenceTitles = Lists.newArrayList(
            1896, 1897, 1901, 1906, 1912,
            1952, 1959, 1962, 1993, 1998,
            1999, 2010, 2011, 2012);

    boolean isSorted = Ordering.natural().isOrdered(uwConferenceTitles);

    assertTrue(isSorted);
}

Strings sorted

@Test
public void is_list_of_strings_sorted_in_java_with_guava () {

    List<String> secConferenceEast = Lists.newArrayList(
            "Florida",
            "Georgia",
            "Missouri",
            "South Carolina",
            "Tennessee",
            "Vanderbilt");

    boolean isSorted = Ordering.natural().isOrdered(secConferenceEast);

    assertTrue(isSorted);
}

Strings sorted decending

@Test
public void is_list_of_strings_sorted_decending_in_java_with_guava () {

    List<String> secConferenceEastDecending = Lists.newArrayList(
            "Vanderbilt",
            "Tennessee",
            "South Carolina",
            "Missouri",
            "Georgia",
            "Florida");

    boolean isSorted = Ordering.natural().reverse().isOrdered(secConferenceEastDecending);

    assertTrue(isSorted);
}

Strings sorted case insensitive

@Test
public void is_list_of_strings_sorted_case_insensitive_in_java_with_guava () {

    List<String> secConferenceEast = Lists.newArrayList(
            "alabama",
            "Alabama",
            "ALABAMA");

    boolean isSorted = Ordering.from(String.CASE_INSENSITIVE_ORDER).isOrdered(secConferenceEast);

    assertTrue(isSorted);
}