gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-12 08:00:36 25 4
gpt4 key购买 nike

这个例子将展示如何使用 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
]

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com