JAVA8学ぶ - 簡単な言葉でラムダ式(学習プロセス)


JAVA8学ぶ - 簡単な言葉でラムダ式(学習プロセス)

ラムダ式:

なぜ我々は、ラムダ式を使用します

  • JAVAでは、我々は、パラメータとして関数に渡され、メソッドの機能を宣言することはできません返すことができません。
  • JavaScriptでは、関数パラメータは関数であり、戻り値は、他の機能は非常に一般的なケースであり、JavaScriptは非常に一般的な関数型プログラミング言語、オブジェクト指向言語であります
//如,JS中的函数作为参数
a.execute(callback(event){
    event...
})

Javaの匿名インナークラスのインスタンス

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

私はGradleのを使用してプロジェクトをビルドするためにここにいます

需要自行补充对Gradle的学习

Gradleは、Mavenのすべての機能を使用することができる
のGradleは、プログラムの設定ファイルに基づいていますMavenのXMLベースの設定ファイルを、.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"));

ラムダ式の基本構造

これは、自動的に関数のパラメータの型を推論します

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

スケーラブルな拡張、ラムダ式の使用

@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メソッド

さらに重要なデータではなく、行動、//アクションの動作です


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

消費者タイプの深さ

名前の由来:消費、だけ消費し、ノーリターン値

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

ラムダ式の役割

  • JAVAとしてラムダ式は、第一級の市民の外観と機能に私達を許可し欠けている機能的なプログラミング機能を追加します
  • 言語のファーストクラス市民としての機能は、ラムダ式のタイプの関数であるが、Java言語で、ラムダ式はオブジェクトであり、それらは、特定のオブジェクト型クラスに取り付けなければならない-関数はインタフェース(関数インタフェースであります)

反復的に(三種類)

外部反復:(反復コレクションを使用する前に、道、本の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の(それ自体はフルセット、内部の反復を介した関数インタフェースを完了するためには、顧客を受け入れる使用することを置きます)

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

第三:方法基準(方法参照)

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

スリープ状態にしようと2019年12月29日午後12時07分05秒。ノートは継続的に更新背後に、コードはGitHubのにアップロードされ、一緒に議論するために歓迎されます。

おすすめ

転載: www.cnblogs.com/bigbaby/p/12113741.html