zoukankan      html  css  js  c++  java
  • Java之Lambda表达式

    在Java中,我们⽆无法将函数作为参数传递给⼀一个 ⽅方法,也⽆无法声明返回⼀一个函数的⽅方法。

    Lambda表达式为Java添加了了缺失的函数式编程特

    性,使我们能将函数当做⼀一等公⺠民看待

    在将函数作为⼀一等公⺠民的语⾔言中,Lambda表达式 的类型是函数。但在Java中,Lambda表达式是对 象,他们必须依附于⼀一类特别的对象类型——函 数式接⼝口(functional interface)

    通常,我们这么写代码

    public static void main(String[] args) {
            System.out.println("hello java8");
    
            JFrame frame = new JFrame("Java窗体");
            JButton button = new JButton("click me");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("JButton clicked");
                }
            });
    
            frame.add(button);
            frame.pack();
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }    

    改成Lambada表达式:

    public static void main(String[] args) {
            System.out.println("hello java8");
    
            JFrame frame = new JFrame("Java窗体");
            JButton button = new JButton("click me");
            button.addActionListener(event -> System.out.println("click me"));
            frame.add(button);
            frame.pack();
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }

    简单明了,言简意感。

    遍历一个数组:

        public static void main(String[] args) {
    
            List<Integer> list = Arrays.asList(1,2,3,4,5,6);
    
            list.forEach(i-> System.out.println("遍历数组:" + i));
        }

  • 相关阅读:
    T-SQL:Varchar和Nvarchar区别(八)
    UI5-文档-4.1-Hello World!
    UI5-文档-4-Walkthrough
    UI5-文档-3-Hello World!
    UI5-文档-2.5-开发混合Web容器
    UI5-文档-2.4-Node.js-Based开发环境
    UI5-文档-2.3-使用SAPUI5工具为Eclipse开发应用程序
    UI5-文档-2.2-使用SAP Web IDE开发应用程序
    UI5-文档-2.1-使用OpenUI5开发应用
    UI5-文档-2-开发环境
  • 原文地址:https://www.cnblogs.com/zhvip/p/12829388.html
Copyright © 2011-2022 走看看