`Collections.replaceAll()` 方法和 `List.replaceAll()` 方法


介面 `Collections` 的 `replaceAll()` 方法接受一個 `List` 物件,兩個型別引數表示舊值和新值,將列表中舊值替換為新值。

示例

 現場演示

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReplaceAllExample {
   public static void main(String args[]) {
      List<String> list = new ArrayList<String>();
      list.add("Java");
      list.add("Java Script");
      list.add("HBase");
      list.add("CoffeeScript");
      list.add("TypeScript");
      System.out.println("Contents of list: "+list);
      Collections.replaceAll(list, "Java", "JAVA");
      System.out.print("Contents of list after replace operation: \n"+list);
   }
}

輸出

Contents of list: [Java, Java Script, HBase, CoffeeScript, TypeScript]
Contents of list after replace operation:
[JAVA, Java Script, HBase, CoffeeScript, TypeScript]

`List` 介面的 `replaceAll()` 方法接受一個表示特定操作的 `UnaryOperator` 物件,對當前列表的所有元素執行指定操作,並將現有值替換為結果值。

示例

 現場演示

import java.util.ArrayList;
import java.util.function.UnaryOperator;
class Op implements UnaryOperator<String> {
   public String apply(String str) {
      return str.toUpperCase();
   }
}
public class Test {
   public static void main(String[] args) throws CloneNotSupportedException {
      ArrayList<String> list = new ArrayList<>();
      list.add("Java");
      list.add("JavaScript");
      list.add("CoffeeScript");
      list.add("HBase");
      list.add("OpenNLP");
      System.out.println("Contents of the list: "+list);
      list.replaceAll(new Op());
      System.out.println("Contents of the list after replace operation: \n"+list);
   }
}

輸出

Contents of the list: [Java, JavaScript, CoffeeScript, HBase, OpenNLP]
Contents of the list after replace operation:
[JAVA, JAVASCRIPT, COFFEESCRIPT, HBASE, OPENNLP]

更新於:2020 年 2 月 24 日

3K+ 瀏覽

開啟你的事業

完成課程獲得認證

開始
廣告
© . All rights reserved.