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
replace elements in a list with another
提问by chaotictranquility
How do I replace elements in a list
with another?
如何将 a 中的元素替换list
为另一个?
For example I want all two
to 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
newVal
each elemente
in 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 boolean
to indicate whether or not any replacement was actually made.
该方法还返回 aboolean
以指示是否实际进行了任何替换。
java.util.Collections
has many more static
utility methods that you can use on List
(e.g. sort
, binarySearch
, shuffle
, etc).
java.util.Collections
还有更多的static
实用方法,你可以使用List
(例如sort
,binarySearch
,shuffle
等)。
Snippet
片段
The following shows how Collections.replaceAll
works; it also shows that you can replace to/from null
as 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]