Reverse elements in list

This example will show how to reverse elements in an arraylist using java, guava and apache commons. In the setup we will create an arraylist using guava's List collection utility passing in various types of precipitation.

Setup

private List<String> precipitation = Lists.newArrayList(
        "Snow",
        "Snow grains",
        "Ice pellets",
        "Hail",
        "Ice crystals",
        "Freezing drizzle",
        "Freezing rain",
        "Rain",
        "Drizzle");

Straight up Java

This snippet will show how to reverse the order of elements in a list using Collections.reverse.

@Test
public void reverse_elements_in_list_java () {

    Collections.reverse(precipitation);

    logger.info(precipitation);

     assertThat(precipitation, contains(
             "Drizzle", "Rain", "Freezing rain",
             "Freezing drizzle", "Ice crystals",
             "Hail", "Ice pellets",
             "Snow grains", "Snow"));
}

Output

[
Drizzle, Rain, Freezing rain,
Freezing drizzle, Ice crystals, Hail,
Ice pellets, Snow grains, Snow
]

Google Guava

This snippet will demonstrate how to reverse an arraylist using guava's Lists.reverse.

@Test
public void reverse_elements_in_list_guava () {

    List<String> reversePrecipitation = Lists.reverse(precipitation);

    assertThat(reversePrecipitation, contains(
             "Drizzle", "Rain", "Freezing rain",
             "Freezing drizzle", "Ice crystals",
             "Hail", "Ice pellets",
             "Snow grains", "Snow"));
}

Output

[
Drizzle, Rain, Freezing rain,
Freezing drizzle, Ice crystals, Hail,
Ice pellets, Snow grains, Snow
]

Apache Commons

This snippet will show how to reverse the order of a list using a loop using apache commons ReverseListIterator. The ReverseListIterator will wrap a list and iterate backwards through a list starting with the last and continuing to the first.

@Test
public void reverse_elements_in_list_apache () {

    ReverseListIterator reverseListIterator = new ReverseListIterator(precipitation);

    List<String> reversePrecipitation = new ArrayList<String>();
    while (reverseListIterator.hasNext()) {
        reversePrecipitation.add( (String) reverseListIterator.next());
    }

    assertThat(reversePrecipitation, contains(
             "Drizzle", "Rain", "Freezing rain",
             "Freezing drizzle", "Ice crystals",
             "Hail", "Ice pellets",
             "Snow grains", "Snow"));
}

Output

[
Drizzle, Rain, Freezing rain,
Freezing drizzle, Ice crystals, Hail,
Ice pellets, Snow grains, Snow
]