java 中的自定义 UnaryOperator 实现。
javaobject oriented programmingprogramming更新于 2025/7/10 13:32:17
java.util.function.UnaryOperator 接口可用作 lambda 表达式的赋值目标,它表示对单个操作数的操作,其结果将与输入的类型相同。我们可以通过实现此接口来创建自己的 UnaryOperator。
List 接口的 replaceAll() 方法接受表示特定操作的 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]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

