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

  • 相关阅读:
    Mysql Got a packet bigger than 'max_allowed_packet' bytes
    Git之IDEA集成Git更新项目Update Type选项解释
    IDEA获取GIT仓库时更新类型update type的选择
    git merge和git rebase的区别
    git merge和git merge --no-ff的区别
    Git中fetch和pull命令的区别
    git官网下载太慢解决方法
    IDEA执行Thread.activeCount() = 2的问题
    k8s 常见错误汇总
    Axure9破解
  • 原文地址:https://www.cnblogs.com/zhvip/p/12829388.html
Copyright © 2011-2022 走看看