UnaryOperator<T> 是 Java 8 中的一个函数式接口,是 Function<T, T> 的子接口。它表示接受一个输入参数和返回值都是相同类型 T 的操作。
以下是 UnaryOperator<T> 接口的用法示例:
import java.util.function.UnaryOperator;
public class UnaryOperatorExample {
public static void main(String[] args) {
// 示例1:对整数进行平方运算
UnaryOperator<Integer> square = num -> num * num;
int result = square.apply(5);
System.out.println(result); // 输出: 25
// 示例2:添加感叹号到字符串末尾
UnaryOperator<String> addExclamation = str -> str + "!";
String text = addExclamation.apply("Hello");
System.out.println(text); // 输出: Hello!
// 示例3:组合多个函数
UnaryOperator<Integer> incrementAndSquare = num -> num + 1;
incrementAndSquare = incrementAndSquare.andThen(square);
result = incrementAndSquare.apply(5);
System.out.println(result); // 输出: 36
}
}
在示例1中,我们创建了一个 UnaryOperator<Integer> 对象 square,用于对整数进行平方运算。通过调用 apply 方法,并将数字 5 作为参数传入,我们可以得到结果 25。
在示例2中,我们创建了一个 UnaryOperator<String> 对象 addExclamation,用于在字符串末尾添加感叹号。通过调用 apply 方法,并将字符串 "Hello" 作为参数传入,我们可以得到结果 "Hello!"。
在示例3中,我们将两个函数 incrementAndSquare 和 square 进行组合。首先将传入的整数加1,然后对结果进行平方运算。通过调用 andThen 方法,我们可以得到一个新的 UnaryOperator 对象 incrementAndSquare,它将传入的整数加1并对结果进行平方运算。最终,通过调用 apply 方法,并将数字 5 作为参数传入,我们可以得到结果 36。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。