Java 用另一个替换列表中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3317691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:03:48  来源:igfitidea点击:

replace elements in a list with another

javalist

提问by chaotictranquility

How do I replace elements in a listwith another?

如何将 a 中的元素替换list为另一个?

For example I want all twoto become one?

例如我想全部two变成one?

采纳答案by polygenelubricants

You can use:

您可以使用:

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

From the documentation:

文档

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

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

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

该方法还返回 aboolean以指示是否实际进行了任何替换。

java.util.Collectionshas many more staticutility methods that you can use on List(e.g. sort, binarySearch, shuffle, etc).

java.util.Collections还有更多的static实用方法,你可以使用List(例如sortbinarySearchshuffle等)。



Snippet

片段

The following shows how Collections.replaceAllworks; it also shows that you can replace to/from nullas well:

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

    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]