zoukankan      html  css  js  c++  java
  • java8中的lambda表达式

    Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
    箭头操作符将 Lambda 表达式拆分成两部分:
    左侧:Lambda 表达式的参数列表
    右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体

    语法格式一:无参数,无返回值

     1 //平时的写法
     2 @Test
     3     public void test1() {
     4         Runnable runnable = new Runnable() {
     5             
     6             @Override
     7             public void run() {
     8         System.out.println("线程启动了");        
     9             }
    10         };
    11         runnable.run();
    12     }
    13   /**
    14    * 语法格式一:无参数,无返回值
    15    *         () -> System.out.println("Hello Lambda!");
    16    */
    17     @Test
    18     public void test2() {
    19         //“->”左边只有一个小括号,表示无参数,右边是Lambda体(就相当于实现了匿名内部类里面的方法了,(即就是一个可用的接口实现类了。))
    20     Runnable runnable = ()->System.out.println("线程启动了");    
    21     runnable.run();
    22     }
    View Code

    语法格式二:有一个参数,并且无返回值

    	(x) -> System.out.println(x)
    

      

    /**语法格式二:有一个参数,并且无返回值
         *         (x) -> System.out.println(x)
         */
        @Test
        public void test3() {
              //这个e就代表所实现的接口的方法的参数,
           Consumer<String> consumer = e->System.out.println("ghijhkhi"+e);
           consumer.accept("woojopj");
        }
    语法格式二:有一个参数,并且无返回值

    当中的底层源代码

     1 /*
     2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     4  */
     5 package java.util.function;
     6 
     7 import java.util.Objects;
     8 
     9 /**
    10  * Represents an operation that accepts a single input argument and returns no
    11  * result. Unlike most other functional interfaces, {@code Consumer} is expected
    12  * to operate via side-effects.
    13  *
    14  * <p>This is a <a href="package-summary.html">functional interface</a>
    15  * whose functional method is {@link #accept(Object)}.
    16  *
    17  * @param <T> the type of the input to the operation
    18  *
    19  * @since 1.8
    20  */
    21 @FunctionalInterface
    22 public interface Consumer<T> {
    23 
    24     /**
    25      * Performs this operation on the given argument.
    26      *
    27      * @param t the input argument
    28      */
    29     void accept(T t);
    30 
    31     /**
    32      * Returns a composed {@code Consumer} that performs, in sequence, this
    33      * operation followed by the {@code after} operation. If performing either
    34      * operation throws an exception, it is relayed to the caller of the
    35      * composed operation.  If performing this operation throws an exception,
    36      * the {@code after} operation will not be performed.
    37      *
    38      * @param after the operation to perform after this operation
    39      * @return a composed {@code Consumer} that performs in sequence this
    40      * operation followed by the {@code after} operation
    41      * @throws NullPointerException if {@code after} is null
    42      */
    43     default Consumer<T> andThen(Consumer<? super T> after) {
    44         Objects.requireNonNull(after);
    45         return (T t) -> { accept(t); after.accept(t); };
    46     }
    47 }
    Consumer的底层实现:

    语法格式三:若只有一个参数,小括号可以省略不写 x -> System.out.println(x)</font(第二种方式的一种简化吧)

    语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句

    public void test4() {
                    //Lambda 体中有多条语句,记得要用大括号括起来
    		Comparator<Integer> com = (x, y) -> {
    		     			System.out.println("函数式接口");
    		     			return Integer.compare(x, y);
    		     		};
    		     		int compare = com.compare(100, 244);
    		     		System.out.println(compare);
    			}
    

     

    语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写 即:Comparator com = (x, y) -> Integer.compare(x, y);

    语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”(Integer x, Integer y) -> Integer.compare(x, y);

    在这里有一点需要说明的:Lambda的表达式,必须要有接口

    方法引用与构造器引用

    方法引用

    当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
    方法引用就是Lambda表达式,就是函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是Lambda表达式的一个语法糖。
    要求:实现抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致!
    方法引用:使用操作符 “::” 将类(或对象) 与 方法名分隔开来。
    如下三种主要使用情况:
    对象::实例方法名
    类::静态方法名
    类::实例方法名

    "实现抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致" 这句话很重要,一定要理解
    我的理解是:
    举个例子
    Comparator comparator = (x,y)->Integer.compare(x, y);等同于
    Comparator comparator1 = Integer::compare;
    即:方法引用的方法是Integer的compare吧,他的参数列表是两个integer类型,返回值是int,这个例子中的抽象方法是Comparator接口的compare()方法

    转自:https://www.cnblogs.com/nnxud/p/9827704.html

  • 相关阅读:
    漫谈程序猿系列:看看你离优秀有多远
    qt学习笔记(五) QGraphicsPixmapItem与QGraphicsScene的编程实例 图标拖动渐变效果
    DropdownList绑定的两种方法
    JUnit入门
    [rxjs] Async, handle data over time
    [rxjs] Creating An Observable with RxJS
    [Javascript + rxjs] Simple drag and drop with Observables
    [Javascript + rxjs] Using the map method with Observable
    [AngularJS] Extract predicate methods into filters for ng-if and ng-show
    [Javascript + rxjs] Introducing the Observable
  • 原文地址:https://www.cnblogs.com/666boyun/p/14040453.html
Copyright © 2011-2022 走看看