美文网首页
Java8 Lamdba表达式

Java8 Lamdba表达式

作者: 海边的蜗牛ng | 来源:发表于2018-06-17 15:45 被阅读0次

Lambda语法定义

可以把Lambda表达式理解为简洁地表示可传递的匿名函数的一种方式:它没有名称,但它
有参数列表、函数主体、返回类型,可能还有一个可以抛出的异常列表。这个定义够大的,让我
们慢慢道来。
 匿名——我们说匿名,是因为它不像普通的方法那样有一个明确的名称:写得少而想
得多!
 函数——我们说它是函数,是因为Lambda函数不像方法那样属于某个特定的类。但和方
法一样,Lambda有参数列表、函数主体、返回类型,还可能有可以抛出的异常列表。
 传递——Lambda表达式可以作为参数传递给方法或存储在变量中。
 简洁——无需像匿名类那样写很多模板代码。

  • Lambda语法测验

根据上述语法规则,以下哪个不是有效的Lambda表达式?

(1) () -> {} 
(2) () -> “Raoul” 
(3) () -> {return “Mario”;} 
(4) (Integer i) -> return “Alan” + i; 
(5) (String s) -> {“IronMan”;}

答案:只有4和5是无效的Lambda。
(1) 这个Lambda没有参数,并返回 void 。它类似于主体为空的方法: public void run() {} 。
(2) 这个Lambda没有参数,并返回 String 作为表达式。
(3) 这个Lambda没有参数,并返回 String (利用显式返回语句)。
(4) return 是 一 个 控 制 流 语 句 。 要 使 此 Lambda 有 效 , 需 要 使 花 括 号 , 如 下 所 示 :
(Integer i) -> {return “Alan” + i;} 。
(5)“Iron Man”是一个表达式,不是一个语句。要使此Lambda有效,你可以去除花括号和分号,如下所示:
(String s) -> “Iron Man” 。或者如果你喜欢,可以使用显式返回语句,如下所示:
(String s)->{return “IronMan”;} 。

  • 函数式接口

函数式接口就是只定义一个抽象方法的接口

函数式接口测验:下面哪些接口是函数式接口?

public interface Adder{ 
int add(int a, int b); 
} 
public interface SmartAdder extends Adder{ 
int add(double a, double b); 
} 
public interface Nothing{ 
}

答案:只有 Adder 是函数式接口。
SmartAdder 不是函数式接口,因为它定义了两个叫作 add 的抽象方法(其中一个是从Adder 那里继承来的)。
Nothing 也不是函数式接口,因为它没有声明抽象方法。

  • 在哪里可以使用Lambda?

以下哪些是使用Lambda表达式的有效方式?

(1) execute(() -> {}); 
public void execute(Runnable r){ 
r.run(); 
} 
(2) 
public Callable fetch() { 
return () -> “Tricky example ;-)”; 
} 
(3) Predicate p = (Apple a) -> a.getWeight();

答案:只有1和2是有效的。
第一个例子有效,是因为Lambda () -> {} 具有签名 () -> void ,这和 Runnable 中的
抽象方法 run 的签名相匹配。请注意,此代码运行后什么都不会做,因为Lambda是空的!
第 二 个 例 子 也 是 有 效 的 。 事 实 上 , fetch 方 法 的 返 回 类 型 是 Callable 。
Callable 基本上就定义了一个方法,签名是 () -> String ,其中 T 被 String 代替 了。因为Lambda () -> “Trickyexample;-)” 的签名是 () -> String ,所以在这个上下文
中可以使用Lambda。
第三个例子无效,因为Lambda表达式 (Apple a) -> a.getWeight() 的签名是 (Apple) ->
Integer ,这和 Predicate:(Apple) -> boolean 中定义的 test 方法的签名不同。

public class FunATest {
    public static void main(String[] args) {


        FunATest funATest = new FunATest();

        //Java8写法
        funATest.execute(() -> { });//也可以什么都不做 毕竟function interface 是Runnable

        funATest.execute(() -> { System.out.printf("A1");System.out.println("A2"); });//多行必须加上{}

        funATest.execute(() -> System.out.println("B1"));//单行可以省略{}
        /*其实 () -> { }就是下面runnable后面的代码,可以看到确实省略了很多呢!*/

        //中正的做法
        Runnable runnable = () -> {
            System.out.println("run = [" + "Runnable" + "]");
        };
        funATest.execute(runnable);

        //以前的写法
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("runnable1.run");
            }
        };
        funATest.execute(runnable1);
    }

    public void execute(Runnable r) {
        new Thread(r).start();
    }
}

函数式接口@FunctionalInterface:
函数式接口定义且只定义了一个抽象method
函数式接口的抽象方法的签名称为函数描
述符。所以为了应用不同的Lambda表达式,你需要一套能够描述常见函数描述符的函数式接口。

Java API中已经有了几个函数式接口

     Predicate<T>——接收T对象并返回boolean
     Consumer<T>——接收T对象,不返回值
     Function<T, R>——接收T对象,返回R对象
     Supplier<T>——提供T对象(例如工厂),不接收值
     naryOperator<T>——接收T对象,返回T对象
     inaryOperator<T>——接收两个T对象,返回T对象

下面的code对几个函数式接口依次举例说明,最后还会对一些特殊函数式接口单独举例说明(如Function

public class FunctionTestA {
    public static void main(String[] args) {
        isDoubleBinaryOperator();
    }

    /**
     * DoubleBinaryOperator double applyAsDouble(double left, double right)
     */
    public static void isDoubleBinaryOperator(){
        DoubleBinaryOperator doubleBinaryOperatorA = (double a,double b) ->  a+b;
        DoubleBinaryOperator doubleBinaryOperatorB = (double a,double b) ->  a-b;
        System.out.println(doubleBinaryOperatorA.applyAsDouble(StrictMath.random()*100,StrictMath.random()*100));
        System.out.println(doubleBinaryOperatorB.applyAsDouble(StrictMath.random()*100,StrictMath.random()*100));
        /**
         * 像类似地DoubleBinaryOperator这样的函数式接口还有很多它们都是被FunctionalInterface注解的函数式接口
         * 被FunctionalInterface注解过的interface必须符合FunctionalInterface规范
         * IntBinaryOperator,LongBinaryOperator等都和BinaryOperator相似
         */
    }

    /**
     * BinaryOperator<T>——接收两个T对象,返回T对象
     */
    public static void isBinaryOperator(){
        BinaryOperator<StringBuilder> binaryOperator = (StringBuilder builder1,StringBuilder builder2) -> {
            builder1.append(builder2);return builder1;
        };
    }

    /**
     * UnaryOperator<T>——接收T对象,返回T对象
     */
    public static void isUnaryOperator(){
        UnaryOperator<User> unaryOperator = (User user) -> {user.setId(4);user.setUsername("alice");return user;};
        User user = unaryOperator.apply(new User());
        System.out.println(user);
    }

    /**
     * Supplier<T>——提供T对象(例如工厂),不接收值
     */
    public static void isSupplier(){
        Supplier<List<User>> supplier = () -> Collections.synchronizedList(new ArrayList<User>());
        List<User> userList = supplier.get();
        userList.add(new User("Blake",5));userList.add(new User("Alice",4));
        System.out.println(userList);
    }

    /**
     * Function<T, R>——接收T对象,返回R对象
     */
    public static void isFunction(){
        String s ="Many other students choose to attend the class, although they will not get any credit. ";
        Function<String,String[]> stringFunction = (String str) -> {return str.split("[^\\w]");};
        String[] strings = stringFunction.apply(s);
        for (String s1:strings) System.out.println(s1);

        Function stream = (S) -> {return new Object();};//奇怪的语法
        Object o = stream.apply("hello");
        System.out.println(o.getClass());
    }

    /**
     * Consumer<T>——接收T对象,不返回值
     */
    public static void isConsumer(){
        Consumer<List> listConsumer = (List list) -> {
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) System.out.println(iterator.next());
        };

        List<String> list = new ArrayList<>(Arrays.asList("Alice","BOb"));
        listConsumer.accept(list);
    }

    /**
     * Predicate<T>——接收T对象并返回boolean
     */
    public static void isPredicate(){
        Predicate<String> predicate = (String s) -> { return s!=null;};
        System.out.println("判断是否为Null:"+predicate.test(null));

        Predicate<Integer> integerPredicate = (Integer a) -> {return (a>10);};
        System.out.println(integerPredicate.test(8));

        Predicate<String[]> predicateStrings = (String...strs) -> {return strs.length >= 3;};
        System.out.println(predicateStrings.test(new String[]{"","",""}));
    }
}

上面对一些函数式接口做了简单的说明,现在看下源码

@FunctionalInterface
public interface Function<T, R> {

    R apply(T t);

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }


    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

可以看到都被@FunctionInterface注解 注解过,因此当我们查看oracle官方手册发现,我们是可以自定义函数式接口的
在定义函数式接口时要注意必须是interface然后是必须是一个method并且是abstract的
现在随便定义一些函数式接口

/**
 * Created by zhou on 18-1-17.
 * 自定义函数接口 FunA
 */
@FunctionalInterface
public interface FunA {
    public int add(int a, int b);
}
/**
 * Created by zhou on 18-1-17.
 * 自定义函数接口 FunB
 */
@FunctionalInterface
public interface FunB {
    public String value(String...strings);
}
/**
 * Created by zhou on 18-1-17.
 * 自定义函数接口FunC
 */
@FunctionalInterface
public interface FunC {
    public void print(String...strings);
}

然后我们在来看一些如何使用

//FunA Lambda表达式
  FunA funA = (int a, int b) -> a + b;
  System.out.println(funA.add(3, 5));

  //FunB Lambda
  String[] strings = {"h", "e", "l", "l", "o"};
  FunB funB = (String... strs) -> {//多行
      StringBuilder builder = new StringBuilder(1024);
      for (String s : strs) builder.append(s);
      return builder.toString();
  };
  System.out.println(funB.value(strings));

  //FunC Lambda
  FunC funC = (String... sts) -> System.out.println(Arrays.toString(sts));
  funC.print("Inspired by a can of tea given to him by one of his Chinese friends in 2004,".split("[^\\w]"));

  Runnable runnable = () -> System.out.println("一个线程!");
  new Thread(runnable).start();

  Predicate<Runnable> predicate = (Runnable r) -> r != null;
  System.out.println(predicate.test(runnable) ? "is not Null" : "is Null");

对单个函数式接口的说明

BinaryOperator<T>——接收两个T对象,返回T对象

UnaryOperator<T>——接收T对象,返回T对象

Function<T, R>——接收T对象,返回R对象
  • 首先Function
/**
     * 主要用来表现一些数学思想
     */
    public static void isFunction() {
        /*下面三者的写法虽然不同,但是思路都完全一致,可以看作Y->X->Z这样一步一步简化而来*/
        //f(x) = x+1
        Function<Integer, Integer> fun1Z = x -> x + 1;//标记Z
        Function<Integer, Integer> fun1X = (Integer x) -> x + 1;//标记X
        Function<Integer, Integer> fun1Y = (Integer x) -> { return x + 1; }; //标记Y

        Function<Integer, Integer> funX = x -> x * 2;
        Function<Integer, Integer> funY = x -> (x * 2) * x + 1;


        //f(x) = x*2 + 1 ==>说明:原本是f(x)=x+1 compose()设x*2 = x代入就得到了f(x) = x*2 + 1 这里要注意的是type 必须一致
        //f1(x) = x+1 , f2(x) = x*2 复合 f1(x) = f2(x) + 1;
        Function<Integer, Integer> fun1 = fun1X.compose(funX);
        System.out.println("(5*2)+1=" + fun1.apply(5));//(5*2)+1
        System.out.println("(6*2)+1=" + fun1.apply(6));//(6*2)+1

        //Function还有一个method andThen
        /*f(x) = x+1 和 f(x) = (x*2)*x+1这两个函数,
        那么andThen的用法是:当前谁调用谁就先执行执行的结果作为参数(或者数学上说的未知数X)传入andThen(fun)中fun的函数中去执行
        因此执行顺序就是fun1Y先执行,得到结果后作为X的值然后funY进行运算
        f(x) = 3+1 ==> x =4 ==>f(x) = (4*2)*4+1=33
        f(x) =((x+1)*2)*(x+1)+1
        */
        fun1 = fun1Y.andThen(funY);
        System.out.println("f(x) =((x+1)*2)*(x+1)+1 ==>((3+1)*2)*(3+1)+1=" + fun1.apply(3));


        //f(x) = x*x , f(x) = x*x*x
        Function<Integer, Long> fun2A = x -> (long) x * x;
        Function<Double, Double> fun2B = x -> x * x * x;
        System.out.println("x*x ==> 4*4=" + fun2A.apply(4) + " ");
    }

打印结果:

(5*2)+1=11
(6*2)+1=13
f(x) =((x+1)*2)*(x+1)+1 ==>((3+1)*2)*(3+1)+1=33
x*x ==> 4*4=16 

相关文章

网友评论

      本文标题:Java8 Lamdba表达式

      本文链接:https://www.haomeiwen.com/subject/ooyweftx.html