开发者

replace elements in a list with another

开发者 https://www.devze.com 2023-01-08 07:55 出处:网络
How d开发者_运维百科o I replace elements in a list with another? For example I want all two to become one?You can use:

How d开发者_运维百科o I replace elements in a list with another?

For example I want all two to become one?


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 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.)

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

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


Snippet

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消