• 【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();
    }
    Ride the wave as long as it will take you.
  • 相关阅读:
    338. 比特位计数
    300.最长上升子序列
    git 钩子服务代码
    thinkphp5.1 封装文件上传模块
    Theano 基础
    使用anaconda和pycharm搭建多python本版的开发环境
    GIT常用命令
    Thinkphp 获取数据表随机值
    在Windows中利用.bat提交git代码到不同分支
    Windows .bat 常量
  • 原文地址:https://www.cnblogs.com/jianpanaq/p/10176628.html
Copyright © 2020-2023  润新知