[TOC]
最近在看一些开源项目的源码,函数式编程风格的代码无处不在,所以得要好好学一下了。
无参数:
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;
每个函数接口列举一些例子来说明。
判断一个数是否为偶数。
Predicate<Integer> isEven = x -> x % 2 == 0; System.out.println(isEven.test(3)); // false
打印字符串。
Consumer<String> printStr = s -> System.out.println("start#" + s + "#end"); printStr.accept("hello"); // start#hello#end List<String> list = new ArrayList<String>(){{ add("hello"); add("world"); }}; list.forEach(printStr);
将数字加1后转换为字符串。
Function<Integer, String> addThenStr = num -> (++num).toString(); String res = addThenStr.apply(3); System.out.println(res); // 4
创建一个获取常用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
实现一元操作符求绝对值。
UnaryOperator<Integer> abs = num -> -num; System.out.println(abs.apply(-3)); // 3
实现二元操作符相加。
BinaryOperator<Integer> multiply = (x, y) -> x * y; System.out.println(multiply.apply(3, 4)); // 12
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。