在Java8中,UnaryOperator是一个参数接口,它继承自Function,UnaryOperator接收一个参数,返回和参数同样类型的结果,其实相当于对数据做了加工。
@FunctionalInterface public interface UnaryOperator<T> extends Function<T, T> { }
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]
标签:总结,java,List,public,util,result,UnaryOperator,Java8 From: https://www.cnblogs.com/jelly12345/p/17374663.html