List.replaceAll(UnaryOperator運算子) 方法在 Java 中


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 年 1 月 10 日

1 千次訪問

開啟你的職業生涯

完成課程以取得認證

開始使用
廣告