pol*_*nts 23
您可以使用:
Collections.replaceAll(list, "two", "one");
Run Code Online (Sandbox Code Playgroud)
从文档:
用列表替换列表中所有出现的指定值.更正式地,替换列表中的
newVal每个元素.(此方法对列表的大小没有影响.)e(oldVal==null ? e==null : oldVal.equals(e))
该方法还返回a boolean以指示是否实际进行了任何替换.
java.util.Collections还有更多static,你可以使用的工具,方法List(例如sort,binarySearch,shuffle等).
以下显示了如何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]
Run Code Online (Sandbox Code Playgroud)