美文网首页
java中的lambda表达式

java中的lambda表达式

作者: 东方未白_ | 来源:发表于2019-05-28 19:02 被阅读0次

    lambda表达式的定义

    Lambda:
    In programming languages such as Lisp, Python and Ruby lambda is an operator used to denote anonymous
    functions or closures, following the usage of lambda calculus

    在编程语言Lisp, Python 和Ruby中,lambda是一种操作符,用于指定匿名函数或者闭包,遵循 λ-calculus

    在Python、JavaScript等函数式编程语言之中,Lambda表达式的类型就是函数。而在Java中,Lambda表达式的类型是对象,必须依附于函数式接口(Functional Interface)。

    java中的lambda表达式是一种匿名函数;没有名字、方法返回值类型以及访问修饰符;

    为何需要lambda表达式

    • Java中无法将函数作为参数传递,一个方法的返回值也不能是一个函数。
    • 写起来简单、优雅,对新人很 友好
    • 编程范式的互相影响以及 借鉴

    基本语法
    ()-> { }

    • 完整的语法是(type1 arg1,type2 arg2)->{body}
    • 小括号内是方法的参数,花括号内是方法的实现,当参数只有一个,实现只有一行时,小括号和花括号都可以省略。

    基本使用示例

    1. 监听Jbutton的点击事件
    public class JavaSwing {
        public static void main(String[] args) {
            JFrame jframe = new JFrame("A Frame");
            JButton jButton = new JButton("A Button");
    //匿名函数写法
            jButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Pressed");
                }
            });
    
    // λ写法
            jButton.addActionListener( e -> System.out.println("Pressed"));
    
            jframe.add(jButton);
            jframe.pack();
            jframe.setVisible(true);
            jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    

    其中 e -> System.out.println("Pressed")
    e代表event,JVM的类型推断认为此处事件一定是一个ActionEvent类型,故可以省略声明 ActionEvent e,从而直接使用变量 e
    list.forEach( i -> System.out.println(i));中的 i 也用到了类型推断。


    2.遍历一个List

    List<Integer> list = Arrays.asList(0,1, 2, 3, 4, 5, 6, 7, 8,9);
    //list.forEach(Integer i -> System.out.println(i));
    list.forEach(i -> System.out.println(i));//JVM根据上文List<Integer>推断出此处 i 的类型为Integer
    

    3.创建一个线程

                new Thread(() -> System.out.println("hello")).start();
    

    相关文章

      网友评论

          本文标题:java中的lambda表达式

          本文链接:https://www.haomeiwen.com/subject/oportctx.html