zoukankan      html  css  js  c++  java
  • 【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.
  • 相关阅读:
    不装.net Framework 也能运行WinForm程序,用飞信(转)
    hdu 1058 Humble Numbers
    c# winform 应用编程代码总结 2
    c# winform 应用编程代码总结 1
    c# winform 应用编程代码总结 4
    住在我隔壁储藏室的大学刚毕业的小夫妻(震撼,转贴)

    CEGUI 0.6.0 Released!
    my ogre plugin for 3dmax
    卡通渲染进阶 = toonlighting + outline + rimlighting + hair specular
  • 原文地址:https://www.cnblogs.com/jianpanaq/p/10176628.html
Copyright © 2011-2022 走看看