Java 8新特性学習ノート(一)Lambda式

4308 ワード

Lambda式の書き方はありません:
 Comparator byYear = new Comparator() {
            @Override            public int compare(Transaction o1, Transaction o2) {                return o1.getValue().compareTo(o2.getValue());
            }
        };

Lambda式の書き方:
 Comparator byYear = (o1, o2) -> o1.getValue().compareTo(o2.getValue());

Lambda式の3つの部分:
  • パラメータリスト ここではComparatorにおけるcomparareの方法のパラメータを採用し,2つのTransaction
  • 矢印    矢印->パラメータリストとLambda本体を区切る.
  • Lambda本体  2つのTransactionの年を比較すると、式はLambdaの戻り値
  • です.
    以下に、Lambdaの例と使用例を示します.
     (List list) -> list.isEmpty();
    () -> new Transaction();
    (Transaction t) -> {
                System.out.println("Year = " + t.getYear());
    }
    (String s) -> s.length();
    (int a, int b) -> a * b;

    Lambdaインタフェースの使用方法
    Lambda式は関数インタフェースで使用できます.
  • 関数式インタフェースは抽象的な方法を定義したインタフェースであり,継承してもだめである. 役割:関数インタフェースの具体的な実装例
  • 例:
         Runnable r2 = new Runnable() {//                 @Override            public void run() {
                    System.out.println("hello world 2");
                }
            };
            process(r1);//  hello world 1
            process(r2);//  hello world 2
            process(()-> System.out.println("hello world 3"));//      Lambda            hello world 3
               java Api,          @FunctionalInterface  ,                    ,        ,            ,            .
    /**
     * The Runnable interface should be implemented by any
     * class whose instances are intended to be executed by a thread. The
     * class must define a method of no arguments called run.
     * 

     * This interface is designed to provide a common protocol for objects that  * wish to execute code while they are active. For example,  * Runnable is implemented by class Thread.  * Being active simply means that a thread has been started and has not  * yet been stopped.  * 

     * In addition, Runnable provides the means for a class to be  * active while not subclassing Thread. A class that implements  * Runnable can run without subclassing Thread  * by instantiating a Thread instance and passing itself in  * as the target.  In most cases, the Runnable interface should  * be used if you are only planning to override the run()  * method and no other Thread methods.  * This is important because classes should not be subclassed  * unless the programmer intends on modifying or enhancing the fundamental  * behavior of the class.  *  * @author  Arthur van Hoff  * @see     java.lang.Thread  * @see     java.util.concurrent.Callable  * @since   JDK1.0 */@FunctionalInterfacepublic interface Runnable {    /**      * When an object implementing interface Runnable is used      * to create a thread, starting the thread causes the object's      * run method to be called in that separately executing      * thread.      * 

         * The general contract of the method run is that it may      * take any action whatsoever.      *      * @see     java.lang.Thread#run()     */     public abstract void run(); }


    メソッド参照
                       ,  Lambda      .         :
    List inventory = new ArrayList<>();
    inventory.sort(Comparator.comparing(Apple::getWeight)//     
     .reversed()//     
     .thenComparing(Apple::getCountry));//            

    メソッド参照を使用する必要がある場合、ターゲット参照は区切り記号::前、メソッド名は後に配置されます.例えば、Apple::getWeightはAppleクラスで定義されたgetWeightを参照しています.カッコは必要ありません.実際にこのメソッドを呼び出す必要はありません.
    メソッド参照には、主に3つの種類があります.
  • 静的方法への参照(例えばIntegerのparseInt方法はInteger::parseIntと書く).
  • 任意のタイプのインスタンスメソッドを指すメソッド参照(例えば、Stringのlengthメソッド、String::lengthと書く)
  • .
  • 既存のオブジェクトのインスタンスメソッドへのメソッド参照(Transactionタイプのオブジェクトを格納するローカル変数expensiveがあると仮定し、インスタンスメソッドgetValueをサポートしている場合は、expensive::getValueと書くことができます).
  • コンストラクタリファレンス
    既存のコンストラクション関数では、名前とキーワードnewを使用して、静的メソッドへの参照タイプと同様の機能を持つClassName::newを作成できます.