如何使用 Java 替换列表中的元素

问题描述

如何替换列表中的元素

解决方案

以下示例使用 replaceAll() 方法将列表中出现的所有元素替换为不同的元素。

import java.util.*;

public class Main {
   public static void main(String[] args) {
      List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
      System.out.println("List :"+list);
      Collections.replaceAll(list, "one", "hundread");
      System.out.println("replaceAll: " + list);
   }
}

结果

上述代码示例将产生以下结果。

List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]
java_collections.html