用另一个替换列表中的元素
如何用另一个替换list
中的元素?
How do I replace elements in a list
with another?
例如,我希望所有two
都成为one
?
For example I want all two
to become one
?
您可以使用:
Collections.replaceAll(list, "two", "one");
来自文档:
将列表中所有出现的一个指定值替换为另一个.更正式地,将列表中的每个元素
e
用newVal
替换为(oldVal==null ? e==null : oldVal.equals(e))
. (此方法对列表的大小没有影响.)
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.)
该方法还返回boolean
来指示是否实际进行了任何替换.
The method also return a boolean
to indicate whether or not any replacement was actually made.
java.util.Collections
还有很多您可以在List
上使用的static
实用程序方法(例如sort
,binarySearch
,shuffle
等).
java.util.Collections
has many more static
utility methods that you can use on List
(e.g. sort
, binarySearch
, shuffle
, etc).
下面显示了Collections.replaceAll
的工作方式;它还表明您也可以替换为null
/:
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]