一、简介
Lambda表达式作为Java8的新特性,目的是为了让方法变得更加简洁,不再需要实现接口就可以执行方法。
实例代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13public static void main(String[] args) { //第一种方式 new Thread(new Runnable() { @Override public void run() { System.out.println("创建一个新的线程"); } }).start(); //第二种方式 new Thread(() -> { System.out.println("创建一个新的线程"); }).start(); }
二、函数式接口的学习
通过上面的代码我们发现Runable是一个函数式接口
函数式接口的必要条件
1.式interface接口
2.有且只有一个抽象方法。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16@FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
例子
当有两个类型 的函数接口无法区分的时候,需要类型转换。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34package com.nw.interfacedemo; /** * 1.类型是接口 * 2.有且只有一个抽象方法。 */ @FunctionalInterface interface InterfaceDemoA { void doSth(); } @FunctionalInterface interface InterfaceDemoB { void doSth(); } public class FunctionDemo { void doSth(InterfaceDemoA interfaceDemo) { System.out.println("function A"); interfaceDemo.doSth(); } void doSth(InterfaceDemoB interfaceDemo) { System.out.println("function B"); interfaceDemo.doSth(); } public static void main(String[] args) { FunctionDemo functionDemo = new FunctionDemo(); functionDemo.doSth((InterfaceDemoA) ()->{ System.out.println("输出一个新东西"); }); //当不知道类型的时候,需要自己确定类型 functionDemo.doSth((InterfaceDemoB)()->{ System.out.println("输出一个新东西"); }); } }
三、jdk常用的函数接口用法
jdk一般的函数接口都位于java.util.function包下面,大家可以都学习一下,常用的要记住相关用法。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25package com.nw.commonfundemo; import java.util.function.*; /** * jdk常用的函数接口 */ public class JdkFunctionDemo { public static void main(String[] args) { //Supplier 没有出入,只有一个输出 Supplier<String> supplier = () -> "this is supplier"; System.out.println(supplier.get()); //Consumer 只有一个输入,没有输出 Consumer<String> consumer = i -> System.out.println("this is demo for" + i); consumer.accept("consumer"); //Function 输入T 输出R Function<Integer, Integer> function = i -> i * i; System.out.println("Funtion demo " + function.apply(12)); //输入输出都是T UnaryOperator<Integer> unaryOperator = i -> i * i; System.out.println("unaryOperator demo " + unaryOperator.apply(12)); //输入T,U,输出R BiFunction<Integer, Integer, String> biFunction = (i, j) -> "this result =" + (i * j); System.out.println("biFunction demo " + biFunction.apply(10, 5)); } }
最后
以上就是健康大地最近收集整理的关于Java流式编程入门学习一、简介二、函数式接口的学习三、jdk常用的函数接口用法的全部内容,更多相关Java流式编程入门学习一、简介二、函数式接口内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复