将列表中的元素替换为另一个列表中的元素

2024-02-24

如何替换 a 中的元素list和另外一个?

例如我想要所有two成为one?


您可以使用:

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

From 文档 http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#replaceAll(java.util.List,%20T,%20T):

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

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

java.util.Collections http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html还有更多static您可以使用的实用方法List (e.g. sort, binarySearch, shuffle, etc).


Snippet

下面展示了如何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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将列表中的元素替换为另一个列表中的元素 的相关文章

随机推荐