【JAVA】lambda表达式

前言

程序员是一群需要不断进化的群体,lambda作为java1.8新出现的功能,所以还是必须要了解的。

格式:循环得到的变量 -> 执行语句

1.集合使用lambda表达式

import java.util.ArrayList;
public class TestSum {

  public static void main(String[] args) {
    ArrayList<String> fruit =new ArrayList<String>();
    fruit.add("apple");
    fruit.add("banana");
    fruit.add("pineapple");
    fruit.forEach(one -> System.out.println(one));
  }
}

2.lambda函数式编程

拿线程来说,如果 不使用lambda表达式,我们要这么写:

public class Test112 {

  public static void main(String[] args) {

    Runnable r = new Runnable() {
      @Override
      public void run() {
        System.out.println("one");
      }
    };
    Thread t = new Thread(r);
    t.start();
    System.out.println("two");
  }
}

如果使用lambda,则变成:

public class Test112 {

  public static void main(String[] args) {

    Runnable r1 = () -> System.out.println("onw");
    Thread t = new Thread(r1);
    t.start();
    System.out.println("two");
  }
}

 如果我们去查看Runnable接口的话会发现Runnable接口只有一个方法,而且是无参的,所有写成()

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

猜你喜欢

转载自www.cnblogs.com/jianpanaq/p/10176628.html
今日推荐