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

13

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

例如,我想将所有的two替换成one

1个回答

23
你可以使用:

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

文档中获取的信息:

将列表中所有指定的值都替换为另一个值。更准确地说,用newVal替换列表中每个元素e,其中(oldVal==null ? e==null : oldVal.equals(e))。(此方法不会影响列表的大小)

该方法还返回一个boolean,以表示是否实际进行了任何替换。

java.util.Collections还有许多可用于List(例如sortbinarySearchshuffle等)的static工具方法。


代码片段

以下是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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接