java.util.function.UnaryOperator接口,可以用作lambda表达式的赋值目标,它表示对单个操作数的操作,其结果与输入的类型相同。我们可以通过实现此接口来创建自己的UnaryOperator。
replaceAll()List接口的方法接受UnaryOperator的对象,该对象表示特定操作对当前列表的所有元素执行指定的操作,并将现有值替换为结果值。
在以下示例中,我们将实现UnaryOperator接口,并创建一个自定义一元运算符对象,然后尝试将其作为参数传递给该replaceAll()方法。
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]