用另一个替换列表中的元素 [英] replace elements in a list with another

查看:67
本文介绍了用另一个替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用另一个替换list中的元素?

How do I replace elements in a list with another?

例如,我希望所有two都成为one?

For example I want all two to become one?

推荐答案

您可以使用:

Collections.replaceAll(list, "two", "one");

来自文档:

将列表中所有出现的一个指定值替换为另一个.更正式地,将列表中的每个元素enewVal替换为(oldVal==null ? e==null : oldVal.equals(e)). (此方法对列表的大小没有影响.)

Replaces all occurrences of one specified value in a list with another. More formally, replaces with newVal each element e in list such that (oldVal==null ? e==null : oldVal.equals(e)). (This method has no effect on the size of the list.)

该方法还返回boolean来指示是否实际进行了任何替换.

The method also return a boolean to indicate whether or not any replacement was actually made.

java.util.Collections 还有很多您可以在List上使用的static实用程序方法(例如sortbinarySearchshuffle等).

java.util.Collections has many more static utility methods that you can use on List (e.g. sort, binarySearch, shuffle, etc).

下面显示了Collections.replaceAll的工作方式;它还表明您也可以替换为null/:

The following shows how Collections.replaceAll works; it also shows that you can replace to/from null as well:

    List<String> list = Arrays.asList(
        "one", "two", "three", null, "two", null, "five"
    );
    System.out.println(list);
    // [one, two, three, null, two, null, five]

    Collections.replaceAll(list, "two", "one");
    System.out.println(list);
    // [one, one, three, null, one, null, five]

    Collections.replaceAll(list, "five", null);
    System.out.println(list);
    // [one, one, three, null, one, null, null]

    Collections.replaceAll(list, null, "none");
    System.out.println(list);
    // [one, one, three, none, one, none, none]

这篇关于用另一个替换列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆