如何用另一个元素替换列表中的元素?
例如,我想将所有的two
替换成one
?
Collections.replaceAll(list, "two", "one");
从文档中获取的信息:
将列表中所有指定的值都替换为另一个值。更准确地说,用
newVal
替换列表中每个元素e
,其中(oldVal==null ? e==null : oldVal.equals(e))
。(此方法不会影响列表的大小)
该方法还返回一个boolean
,以表示是否实际进行了任何替换。
java.util.Collections
还有许多可用于List
(例如sort
,binarySearch
,shuffle
等)的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]