jdk1.8 lambda理解

jdk1.8的理解


之前线上的jdk1.7的,登录许久终于等到1.8的新项目, 终于可以用lambda表达式啦哈哈哈哈~~~

  • 匿名类

对于一些接口,我们可以采用使用 new的方式创建

# 这个不是匿名类
 Runnable runnable = new Runnable(){
  public void run(){
    System.out.prinln("this is a new Thread");
  }
}

new Thread(runnable).start();

# 这个就是匿名类。。 没有名类名的类
new Thread(
    new Runnable(){
      public void run(){
        System.out.prinln("this is a new Thread");
      }
    }
).start();

lambda表达式


我的理解就是 lambda就是针对于 匿名类来的。。
比如上面的 Runnable 接口定义如下: 可以简单理解就是 一个接口里面就一个方法, 这种接口叫做 《函数式接口》, 这个方法的 入参是什么(这里是无参) 返回是什么类型(这是是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();
}

对于没有入参,没有返回值的 接口函数 lambda如下:

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

对于 lambda的理解, 这就是一个 匿名类的实现。 就和 new Runnable(){} 一样。 不过就是 lambda表达式里面是否需要参数,和返回值是否需要, 需要靠 接口 里面的 那个方法决定。


  • Consumer

源码如下:

@FunctionalInterface
public interface Consumer<T> {

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

这时候 你创建lambda表达式的时候 就需要 有一个参数啦。。

Consumer<Integer> c = (a)->{System.out.println(a);}
# 调用
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);

这时候 你创建lambda表达式的时候 就需要 有一个参数啦。。

Predicate<Integer> p = (a)->{return a>10;}
//或者
Predicate<Integer> p1 = (a)-> a>10
# 调用
p.test(23);
// 输出 true

  • Supplier

这个东西呢,废话不多说,先看源码

@FunctionalInterface
public interface Supplier<T> {

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

lambda是 什么入参都没有,但是返回一个对象

Supplier<User> s = ()->new User(); 
//这样就搞定啦。。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。