JAVA8 learn - in simple terms Lambda expressions (the learning process)


JAVA8 learn - in simple terms Lambda expressions (the learning process)

lambda expression:

Why do we use a lambda expression

  • In JAVA, we can not be passed to a function as a parameter and returns a function of the method can not be declared.
  • In JavaScript, the function parameter is a function, the return value is the case where another function very common, JavaScript is a very typical functional programming languages, object-oriented language
//如,JS中的函数作为参数
a.execute(callback(event){
    event...
})

Java anonymous inner class instances

后面补充一个匿名内部类的代码实例

I am here to build the project using Gradle

需要自行补充对Gradle的学习

Gradle can use all the capabilities of the Maven
Maven XML-based configuration files, Gradle is based on programmatic configuration file .Gradle

Custom anonymous inner classes

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

Transformation of the former:

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

After transformation:

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

The basic structure of Lambda expressions

It will automatically infer the type of function parameters

(pram1,pram2,pram3)->{
    
}

Functional Interface

概念后期补(接口文档源码,注解源码)
抽象方法,抽象接口
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接口,编译器也还会把该接口当做成一个函数是接口。(英文最后一段)

For example by deep understanding of the function interface

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

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

    String tostring1();
}

对 (tostring为重写Object类的方法)
@FunctionalInterface
public interface MyInterface {
    void test();

    String toString();
}

Scalable expansion, the use of lambda expressions

@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]);// 查看此类实现的接口
    }
}

The default method: an interface inside, start from 1.8, you can also have a way to achieve.

The default method not only ensures add new features, but also to ensure compatibility with older versions of

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

Detailed ForEach method

More important is the behavior, // action behavior, rather than data


/**
     * 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 Type In Depth

The origin of the name: consumption, consuming only, no return value

/**
 * 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 expressions role

  • Lambda expressions as JAVA add the missing functional programming features that allow us to function as first-class citizens look
  • Function as first-class citizens in the language, is a function of the type of Lambda expressions, but in JAVA language, the lambda expression is an object , they must be attached to a particular object type class - function is the interface (function interface )

In an iterative manner (three kinds)

External iteration :( way before using iterative collection, fori of this)

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

Internal iteration: ForEach (full set per se, to complete the function interface via internal iterations put to use the Accept Customer)

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

Third: The method reference (method reference)

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

December 29, 2019 00:07:05 trying to sleep. Behind the notes continuously updated, the code will be uploaded to GitHub, and welcome to discuss together.

Guess you like

Origin www.cnblogs.com/bigbaby/p/12113741.html