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

原文地址:https://www.cnblogs.com/zhvip/p/12829388.html