Lambda表达式
来自CloudWiki
函数式接口
函数式接口(Functional Interfaces):如果一个接口定义个唯一一个抽象方法,那么这个接口就成为函数式接口。例如ActionListener接口。
比如说,ActionListener接口的一个实现类:
private class ColorAction implements ActionListener{ private Color bgColor; public ColorAction(Color bgColor){ this.bgColor = bgColor; } @Override public void actionPerformed(ActionEvent e) { buttonPanel.setBackground(bgColor); } }
Lambda表达式
Lambda表达式是jdk1.8发布的新特性,可以让你的代码更加的简洁。Lambda无法单独出现,需要一个函数式接口来盛放,可以说lambda表达式方法体是函数式接口的实现,lambda实例化函数式接口,可以将函数作为方法参数,或者将代码作为数据对待。
语法
(parameters)->expression 或者 (parameters)->{statements;}
Lambda表达式由三部分组成:
- parameters:类似方法中的形参列表,这里的参数是函数式接口里的参数。这里的参数类型可以明确的声明也可不声明而由JVM隐含的推断,当只有一个推断类型时可以省略掉圆括号。
- -> :可以理解为“被用于”的意思
- 方法体:可以是表达式也可以是代码块,实现函数式接口中的方法。这个方法体可以有返回值也可以没有返回值
例如:如下程序实现了两个数字的计算:
public class TestLambda { //定义了一个数学运算的接口,可被用于两个操作数的加减乘除运算 interface IntegerMath { int operation(int a, int b); } //定义了一个数学运算的方法,刚才定义的接口作为参数传进来 public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } public static void main(String... args) { TestLambda myApp = new TestLambda(); IntegerMath addition = (a, b) -> a + b;//lambda表达式, 用减法实现刚才的接口,隐式推断类型 IntegerMath subtraction = (int a, int b) -> a - b;// lambda表达式,用加法实现刚才的接口 显式声明类型 System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } }
程序执行结果如下:
使用Lambda简化事件处理代码
在上一小节的例子中,程序为事件监听器实现的接口ActionListener是函数式接口,在这种情况下,使用Lamba表达式可以极大的简化代码:
下面程序使用Lambda表达式修改来设置窗口背景色:
public class BackGroundColorLambda extends JFrame { private JButton btRed; private JButton btGreen; private JButton btBlue; JPanel buttonPanel; public BackGroundColorLambda(){ super("改变颜色"); btRed = new JButton("红色"); btGreen = new JButton("绿色"); btBlue = new JButton("蓝色"); btRed.addActionListener(e->buttonPanel.setBackground(Color.RED)); btGreen.addActionListener(e->buttonPanel.setBackground(Color.GREEN)); btBlue.addActionListener(e->buttonPanel.setBackground(Color.BLUE)); buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); buttonPanel.add(btRed); buttonPanel.add(btGreen); buttonPanel.add(btBlue); add(buttonPanel); setSize(300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { BackGroundColorLambda bg = new BackGroundColorLambda(); } }
返回 Java程序设计