如何使用 java、guava 和 apache commons实现Arraylist列表的反转

x33g5p2x  于2022-09-15 转载在 Java  
字(2.0k)|赞(0)|评价(0)|浏览(325)

这个例子将展示如何使用 java、guava 和 apache commons实现Arraylist列表的反转。

示例数据

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

原生Java

此代码段将展示如何使用 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"));
}

输出

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

Google Guava

该片段将演示如何使用 guava 的 Lists.reverse 反转 arraylist。

@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"));
}

输出

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

Apache Commons

这个片段将展示如何使用 apache commons ReverseListIterator 使用循环来反转列表的顺序。 ReverseListIterator 将包装一个列表并从最后一个列表开始并继续到第一个列表向后迭代。

@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"));
}

输出

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

相关文章

微信公众号

最新文章

更多