jdk1.8 lambda理解

jdk1.8的理解


之前線上的jdk1.7的,登錄許久終于等到1.8的新項(xiàng)目, 終于可以用lambda表達(dá)式啦哈哈哈哈~~~

  • 匿名類

對(duì)于一些接口,我們可以采用使用 new的方式創(chuàng)建

# 這個(gè)不是匿名類
 Runnable runnable = new Runnable(){
  public void run(){
    System.out.prinln("this is a new Thread");
  }
}

new Thread(runnable).start();

# 這個(gè)就是匿名類。。 沒有名類名的類
new Thread(
    new Runnable(){
      public void run(){
        System.out.prinln("this is a new Thread");
      }
    }
).start();

lambda表達(dá)式


我的理解就是 lambda就是針對(duì)于 匿名類來的。。
比如上面的 Runnable 接口定義如下: 可以簡(jiǎn)單理解就是 一個(gè)接口里面就一個(gè)方法, 這種接口叫做 《函數(shù)式接口》, 這個(gè)方法的 入?yún)⑹鞘裁矗ㄟ@里是無參) 返回是什么類型(這是是void)

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

對(duì)于沒有入?yún)?,沒有返回值的 接口函數(shù) lambda如下:

  () - >{log.info("this is test")}  # 

對(duì)于 lambda的理解, 這就是一個(gè) 匿名類的實(shí)現(xiàn)。 就和 new Runnable(){} 一樣。 不過就是 lambda表達(dá)式里面是否需要參數(shù),和返回值是否需要, 需要靠 接口 里面的 那個(gè)方法決定。


  • Consumer

源碼如下:

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
}

這時(shí)候 你創(chuàng)建lambda表達(dá)式的時(shí)候 就需要 有一個(gè)參數(shù)啦。。

Consumer<Integer> c = (a)->{System.out.println(a);}
# 調(diào)用
c.accept(1); 
// 輸出 1

  • Predicate

源碼如下:

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

這時(shí)候 你創(chuàng)建lambda表達(dá)式的時(shí)候 就需要 有一個(gè)參數(shù)啦。。

Predicate<Integer> p = (a)->{return a>10;}
//或者
Predicate<Integer> p1 = (a)-> a>10
# 調(diào)用
p.test(23);
// 輸出 true

  • Supplier

這個(gè)東西呢,廢話不多說,先看源碼

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

lambda是 什么入?yún)⒍紱]有,但是返回一個(gè)對(duì)象

Supplier<User> s = ()->new User(); 
//這樣就搞定啦。。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容