UnaryOperator示例
在Java8中,UnaryOperator是一个参数接口,它继承自Function
UnaryOperator接收一个参数,返回和参数同样类型的结果
UnaryOperator.java
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
}
Function接收任意类型的类型,返回任意类型的结果
Function.java
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
UnaryOperator
下面示例中,Function<Integer, Integer>接收和返回结果是相同类型,因此可以用UnaryOperator替换
import java.util.function.Function;
import java.util.function.UnaryOperator;
public class Java8UnaryOperator1 {
public static void main(String[] args) {
Function<Integer, Integer> func = x -> x * 2;
Integer result = func.apply(2);
System.out.println(result); // 4
UnaryOperator<Integer> func2 = x -> x * 2;
Integer result2 = func2.apply(2);
System.out.println(result2); // 4
}
}
输出
4
4
UnaryOperator作为参数
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.UnaryOperator;
public class Java8UnaryOperator2 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> result = math(list, x -> x * 2);
System.out.println(result); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
}
public static <T> List<T> math(List<T> list, UnaryOperator<T> uo) {
List<T> result = new ArrayList<>();
for (T t : list) {
result.add(uo.apply(t));
}
return result;
}
}
输出
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
链式UnaryOperator
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.UnaryOperator;
public class Java8UnaryOperator3 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> result = math(list,
x -> x * 2,
x -> x + 1);
System.out.println(result); // [3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
}
public static <T> List<T> math(List<T> list,
UnaryOperator<T> uo, UnaryOperator<T> uo2) {
List<T> result = new ArrayList<>();
for (T t : list) {
result.add(uo.andThen(uo2).apply(t));
}
return result;
}
}
输出
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]