1. 程式人生 > >JAVA8學習——深入淺出Lambda表示式(學習過程)

JAVA8學習——深入淺出Lambda表示式(學習過程)


JAVA8學習——深入淺出Lambda表示式(學習過程)

lambda表示式:

我們為什麼要用lambda表示式

  • 在JAVA中,我們無法將函式作為引數傳遞給一個方法,也無法宣告返回一個函式的方法。
  • 在JavaScript中,函式引數是一個函式,返回值是另一個函式的情況下非常常見的,JavaScript是一門非常典型的函數語言程式設計語言,面向物件的語言
//如,JS中的函式作為引數
a.execute(callback(event){
    event...
})

Java匿名內部類例項

後面補充一個匿名內部類的程式碼例項

我這裡Gradle的使用來構建專案

需要自行補充對Gradle的學習

Gradle完全可以使用Maven的所有能力
Maven基於XML的配置檔案,Gradle是基於程式設計式配置.Gradle檔案

自定義匿名內部類

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);
    }
}

改造前:

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

改造後:

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

Lambda表示式的基本結構

會有自動推斷引數型別的功能

(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,歡迎一起學習討論