Java8函数式编程(一):Lambda表达式类型与常用函数接口
[TOC]
1 前言
最近在看一些开源项目的源码,函数式编程风格的代码无处不在,所以得要好好学一下了。
2 Lambda表达式类型无参数:
Runnable noArguments = () -> System.out.println("Hello World!");noArguments.run();
一个参数:
UnaryOperator<Boolean> oneArgument = x -> !x;System.out.println(oneArgument.apply(true));
多行语句:
Runnable multiStatement = () -> { System.out.print("Hello"); System.out.println(" World!");};
两个参数:
BinaryOperator<Integer> add = (x, y) -> x + y;add.apply(1, 2);
显式类型:
BinaryOperator<Integer> addExplicit = (Integer x, Integer y) -> x + y;
3 常用函数接口
每个函数接口列举一些例子来说明。
3.1 Predicate<T>判断一个数是否为偶数。
Predicate<Integer> isEven = x -> x % 2 == 0;System.out.println(isEven.test(3)); // false
3.2 Consumer<T>
打印字符串。
Consumer<String> printStr = s -> System.out.println("start#" + s + "#end");printStr.accept("hello"); // start#hello#endList<String> list = new ArrayList<String>(){{ add("hello"); add("world");}};list.forEach(printStr);
3.3 Function<T,R>
将数字加1后转换为字符串。
Function<Integer, String> addThenStr = num -> (++num).toString();String res = addThenStr.apply(3);System.out.println(res); // 4
3.4 Supplier<T>
创建一个获取常用SimpleDateFormat的Lambda表达式。
Supplier<SimpleDateFormat> normalDateFormat = () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");SimpleDateFormat sdf = normalDateFormat.get();Date date = sdf.parse("2019-03-29 23:24:05");System.out.println(date); // Fri Mar 29 23:24:05 CST 2019
3.5 UnaryOperator<T>
实现一元操作符求绝对值。
UnaryOperator<Integer> abs = num -> -num;System.out.println(abs.apply(-3)); // 3
3.6 BinaryOperator<T>
实现二元操作符相加。
BinaryOperator<Integer> multiply = (x, y) -> x * y;System.out.println(multiply.apply(3, 4)); // 12
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。