如何在 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.htm
广告
© . All rights reserved.