JAVA 8学習——深くて浅くてLamband表現(学習過程)

12257 ワード

JAVA 8学習——深くて浅くてLamband表現(学習過程)
lamda表現:
なぜ私たちはラダ式を使いますか?
  • JAVAでは、関数をパラメータとして渡したり、関数を返す方法を説明することができません。
  • JavaScriptでは、関数パラメータが関数であり、戻り値が別の関数の場合によく見られます。JavaScriptは非常に典型的な関数式プログラミング言語で、対象に向けた言語
  • // ,JS        
    a.execute(callback(event){
        event...
    })
    Java匿名内部クラスの例
                    
    私はここのGraadleを使ってプロジェクトを構築します。
           Gradle   
    GraadleはMavenのすべての能力を使用することができます。MavenはXMLベースのプロファイルです。Graadleはプログラミングベースの配置です。Gradeファイルです。
    匿名の内部クラスをカスタマイズ
    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"));
    Lamda表現の基本構造
    パラメータの種類を自動的に推定する機能があります。
    (pram1,pram2,pram3)->{
        
    }
    関数インターフェース
         (      ,    )
        ,    
    1             ,          
    
    /**
     * An informative annotation type used to indicate that an interface
     * type declaration is intended to be a functional interface 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
     * not 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.
     *
     * 

    Note that instances of functional interfaces can be created with * lambda expressions, method references, or constructor references. * *

    If a type is annotated with this annotation type, compilers are * required to generate an error message unless: * *

      *
    • The type is an interface type and not an annotation type, enum, or class. *
    • The annotated type satisfies the requirements of a functional interface. *
    * *

    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();
    }
    拡張機能をアップグレードして、lamda式を使用します。
    @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 {
        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
         * 

    The default implementation behaves as if: *

    {@code
         *     for (T t : this)
         *         action.accept(t);
         * }

    *@param action The action to be performed for each element
    *@throws Null PointerException if the specified action is null
    *@since 1.8
    */
    default void forEach(Consmer super T>action){
    Objects.require NonNull(action);
    for(T t:this){
    action.accept(t)
    )
    )
    Consmerタイプの
    の : は、 だけで、 り がないからです。
    /**
     * 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.//           ,             
     *
     * 

    This is a functional interface * whose functional method is {@link #accept(Object)}. * * @param the type of the input to the operation * * @since 1.8 */ @FunctionalInterface public interface Consumer { /** * 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 andThen(Consumer super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; } }

    Lamda の
  • Lambada はJAVAに した プログラミング を しており、 を として うことができる
  • を とする では、Lamber の は であるが、JAVA では、lambada は となり、 なオブジェクトタイプに しなければならない。 はインターフェース
  • (3つ)
    :( に された の でforiという)
    List 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 list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
    list.forEach(i -> System.out.println(i));
    の : (method reference)
    List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
    list.forEach(System.out::println);
    の はただlamda の で、 の はあなたが っているほど ではありません。
    なぜJAVAでのラボダ が なのかを します。
    //    ,JAVA lambda        
    public class Test3 {
        public static void main(String[] args) {
    
            //         1.lambda     ()      {}     
            TheInterface i1 = () -> {};
            System.out.println(i1.getClass().getInterfaces()[0]);
    
            TheInterface2 i2 = () -> {};
            System.out.println(i2.getClass().getInterfaces()[0]);
    
            //        ,        。   lambda      ,          。
            //() -> {};
    
    
            //  lambda      。     //Runnable runnable;               
            new Thread(()->{
                System.out.println("hello world");
            }).start();
    
    
            //    ,    ,    ,  ,  
            List list = Arrays.asList("hello","worild","hello world");
            list.forEach(item ->{
                System.out.println(item.toUpperCase());
            });
    
            // list      ,  list1 ,    
            List list1 = new ArrayList<>(); //diamond             
            list.forEach(item -> list1.add(item.toUpperCase()));
            list1.forEach(System.out::println);
    
            //    ,         。   lambda   ,  ,    。             
    //        list.stream().map(item -> item.toUpperCase()).forEach(item-> System.out.println(item.toUpperCase()));
            list.stream().map(String::toUpperCase).forEach(System.out::println);
            
        }
    }
    
    @FunctionalInterface
    interface TheInterface{
        void myMethod();
    }
    
    @FunctionalInterface
    interface TheInterface2{
        void myMethod2();
    }
    
    
    に な をする。
    /**
         * Returns a sequential {@code Stream} with this collection as its source.
         *
         * 

    This method should be overridden when the {@link #spliterator()} * method cannot return a spliterator that is {@code IMMUTABLE}, * {@code CONCURRENT}, or late-binding. (See {@link #spliterator()} * for details.) * * @implSpec * The default implementation creates a sequential {@code Stream} from the * collection's {@code Spliterator}. * * @return a sequential {@code Stream} over the elements in this collection * @since 1.8 */ default Stream stream() { return StreamSupport.stream(spliterator(), false); } /** * Returns a possibly parallel {@code Stream} with this collection as its * source. It is allowable for this method to return a sequential stream. * *

    This method should be overridden when the {@link #spliterator()} * method cannot return a spliterator that is {@code IMMUTABLE}, * {@code CONCURRENT}, or late-binding. (See {@link #spliterator()} * for details.) * * @implSpec * The default implementation creates a parallel {@code Stream} from the * collection's {@code Spliterator}. * * @return a possibly parallel {@code Stream} over the elements in this * collection * @since 1.8 */ default Stream parallelStream() { return StreamSupport.stream(spliterator(), true); }

    シリアルストリーム、パラレルストリーム、ノードストリームPipeline (Linuxの )
    ストリームはソースが です。
    Lamda の
  • は、
  • レベルの
  • APIの が い
  • より
  • め りをつける
    Java Lambada
  • JAVAでのlamda の
  • ( )-){body}
  • JAVAラバンダ
  • 1つのlamda は、0つ のパラメータ
  • パラメータの は、 に しても いし、 から しても い
  • てのパラメータは に め、パラメータ はカンマで られる がある
  • かっこ パラメータセットが
  • パラメータが つしかなく、そのタイプが できる は、 ()は することができます。
  • mbda の には、ゼロまたは の が まれています
  • ラボダ の が つの しかない 、 {}は できます。 の りの は、 と する
  • ラボダ の に つ の が まれている 、 は {}にコードブロックを めなければなりません。 の りのタイプは、コードブロックの りのタイプと しており、 りがない は となる。
  • 2019 12 29 00:07:05は ます。メモの は に します。コードはGitHubにアップロードされます。 に してください。