JAVA8學習——深刻淺出Lambda表達式(學習過程)


JAVA8學習——深刻淺出Lambda表達式(學習過程)

lambda表達式:

咱們爲何要用lambda表達式

  • 在JAVA中,咱們沒法將函數做爲參數傳遞給一個方法,也沒法聲明返回一個函數的方法。
  • 在JavaScript中,函數參數是一個函數,返回值是另外一個函數的狀況下很是常見的,JavaScript是一門很是典型的函數式編程語言,面向對象的語言
//如,JS中的函數做爲參數
a.execute(callback(event){
    event...
})

Java匿名內部類實例html

後面補充一個匿名內部類的代碼實例

我這裏Gradle的使用來構建項目java

須要自行補充對Gradle的學習

Gradle徹底可使用Maven的全部能力
Maven基於XML的配置文件,Gradle是基於編程式配置.Gradle文件express

自定義匿名內部類編程

public class SwingTest {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("my Frame");
        JButton jButton = new JButton("My Button");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Button Pressed");
            }
        });
        jFrame.add(jButton);
        jFrame.pack();
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

改造前:less

jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Button Pressed");
            }
        });

改造後:編程語言

jButton.addActionListener(actionEvent -> System.out.println("Button Pressed"));

Lambda表達式的基本結構

會有自動推斷參數類型的功能ide

(pram1,pram2,pram3)->{
    
}

函數式接口

概念後期補(接口文檔源碼,註解源碼)
抽象方法,抽象接口
1個接口裏面只有一個抽象方法,能夠有幾個具體的方法

/**
 * An informative annotation type used to indicate that an interface
 * type declaration is intended to be a <i>functional interface</i> as
 * defined by the Java Language Specification.
 *
 * Conceptually, a functional interface has exactly one abstract
 * method.  Since {@linkplain java.lang.reflect.Method#isDefault()
 * default methods} have an implementation, they are not abstract.  If
 * an interface declares an abstract method overriding one of the
 * public methods of {@code java.lang.Object}, that also does
 * <em>not</em> count toward the interface's abstract method count
 * since any implementation of the interface will have an
 * implementation from {@code java.lang.Object} or elsewhere.
 *
 * <p>Note that instances of functional interfaces can be created with
 * lambda expressions, method references, or constructor references.
 *
 * <p>If a type is annotated with this annotation type, compilers are
 * required to generate an error message unless:
 *
 * <ul>
 * <li> The type is an interface type and not an annotation type, enum, or class.
 * <li> The annotated type satisfies the requirements of a functional interface.
 * </ul>
 *
 * <p>However, the compiler will treat any interface meeting the
 * definition of a functional interface as a functional interface
 * regardless of whether or not a {@code FunctionalInterface}
 * annotation is present on the interface declaration.
 * 
 * @jls 4.3.2. The Class Object
 * @jls 9.8 Functional Interfaces
 * @jls 9.4.3 Interface Method Body
 * @since 1.8
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}


關於函數式接口:
1.如何一個接口只有一個抽象方法,那麼這個接口就是函數式接口
2.若是咱們在某個接口上生命了FunctionalInterface註解,那麼編譯器就會按照函數式接口的定義來要求該註解
3.若是某個接口只有一個抽象方法,但咱們沒有給該接口生命FunctionalInterface接口,編譯器也還會把該接口當作成一個函數是接口。(英文最後一段)

經過對實例對函數式接口深刻理解函數式編程

對
@FunctionalInterface
public interface MyInterface {
    void test();
}

錯
@FunctionalInterface
public interface MyInterface {
    void test();

    String tostring1();
}

對 (tostring爲重寫Object類的方法)
@FunctionalInterface
public interface MyInterface {
    void test();

    String toString();
}

升級擴展,使用lambda表達式函數

@FunctionalInterface
interface MyInterface {
    void test();

    String toString();
}

public class Test2{
    public void myTest(MyInterface myInterface){
        System.out.println("1");
        myInterface.test();
        System.out.println("2");
    }

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        //1.默認調用接口裏面的接口函數。默認調用MyTest接口裏面的test方法。
        //2.若是沒有參數傳入方法,那麼能夠直接使用()來表達,以下所示
        test2.myTest(()-> System.out.println("mytest"));
        
        MyInterface myInterface = () -> {
            System.out.println("hello");
        };

        System.out.println(myInterface.getClass()); //查看這個類
        System.out.println(myInterface.getClass().getSuperclass());//查看類的父類
        System.out.println(myInterface.getClass().getInterfaces()[0]);// 查看此類實現的接口
    }
}

默認方法:接口裏面,從1.8開始,也能夠擁有方法實現了。

默認方法既保證了新特性的添加,又保證了老版本的兼容學習

//如,Iterable 中的 forEach方法
public interface Iterable<T> {
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
}

ForEach方法詳解

比較重要的是行爲,//action行爲,而不是數據

/**
     * Performs the given action for each element of the {@code Iterable}
     * until all elements have been processed or the action throws an
     * exception.  Unless otherwise specified by the implementing class,
     * actions are performed in the order of iteration (if an iteration order
     * is specified).  Exceptions thrown by the action are relayed to the
     * caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     for (T t : this)
     *         action.accept(t);
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if the specified action is null
     * @since 1.8
     */
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

Consumer 類型詳解

名字的由來:消費,只消費,沒有返回值

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.//接口自己是帶有反作用的,會對傳入的惟一參數進行修改
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Lambda表達式的做用

  • Lambda表達式爲JAVA添加了缺失的函數式編程特性,使咱們可以將函數當作一等公民看待
  • 在將函數做爲一等公民的語言中,Lambda表達式的類型是函數,可是在JAVA語言中,lambda表達式是一個對象,他們必須依附於一類特別的對象類型——函數是接口(function interface)

迭代方式(三種)

外部迭代:(以前使用的迭代集合的方式,fori這種的)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

內部迭代: ForEach(徹底經過集合的自己,經過函數式接口拿出來使用Customer的Accept來完成內部迭代)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
list.forEach(i -> System.out.println(i));

第三種方式:方法引用(method reference)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
list.forEach(System.out::println);

2019年12月29日00:07:05 要睡覺了。筆記後面持續更新,代碼會上傳到GitHub,歡迎一塊兒學習討論。

相關文章
相關標籤/搜索