您可以使用:
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]