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

  • 相关阅读:
    maven学习(中)- 私服nexus搭建
    批量kill相关所有进程
    install kinect driver for ARM---38
    install usb serial
    用真实的机器人做人脸跟踪器---37
    PCL Nodelets 和 3D 点云---36
    在程序中访问骨架图---35
    openni和骨架追踪 rviz查看---34
    颜色追踪块CamShift---33
    动态的添加和丢弃关键点---32
  • 原文地址:https://www.cnblogs.com/zhvip/p/12829388.html
Copyright © 2011-2022 走看看