`

Java 8 – Lambda Expressions

阅读更多
A lambda expression is basically just a block of code that you can pass around to be executed later – once, or multiple times. Many other languages support them, so you’ve probably already used them if you’ve coded in a language other than C/C++/Java/C# (they’re also often referred to as ‘Closures’, ‘Anonymous Functions’, or ‘Blocks’).

 

A quick example to show the syntax: sorting list of custom elements

Often you would solve this by defining an anonymous inner class that implements the Comparator interface. With Java 8, you can instead provide a lambda expression that defines the comparison:

 

You have a list (dateItems) of objects that have a member of type Date.

 

List<DatedItem> dateItems = <…get items…>

dateItems.sort( (DatedItem a, DatedItem b) -> { returna.date().compareTo(b.date() } );

 

 

Syntax

-          General structure: ( arguments ) -> { body }

-          A left and right side separated by a -> token. The left side defines the incoming parameters. The right side defines the code to execute.

-          A lambda expression can have zero, one or more parameters.

-          The type of the parameters can be explicitly declared or it can be inferred from the context. e.g. (int a) is same as just (a)

-           Parameters are enclosed in parentheses and separated by commas. e.g. (a, b) or (int a, int b) or (String a, int b, float c)

-           Empty parentheses are used to represent an empty set of parameters. e.g. () -> 42

-           When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. a -> return a*a

-          The body of the lambda expressions can contain zero, one or more statements.

-          If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.

-          When there is more than one statement in body than these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.

 

Functional Interfaces

A ‘functional interface’ is an interface that declares a single abstract method. For example java.lang.Runnable (declares only run() method), or java.awt.event.ActionListener (declares only actionPerformed(ActionEvent) method). Wherever a functional interface is used, a lambda can be used in its place. E.g. :

 

newThread( () -> System.out.println("thread started") ).start();

 

Examples

 

-- Thread execution --

//Old way:

new Thread(new Runnable() {

    @Override

    public void run() {

        System.out.println("Hello from thread");

    }

}).start();

 

//New way:

new Thread( () -> System.out.println("Hello from thread") ).start();

 

-- Button handling --

//Old way:

button.addActionListener(new ActionListener() {

    @Override

    public void actionPerformed(ActionEvent e) {

        System.out.println("The button was clicked using old fashion code!");

    }

});

 

//New way:

button.addActionListener( (e) -> { System.out.println("The button was clicked. From lambda expressions !"); });

 

-- List processing --

//Old way:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

for(Integer n: list) {

    System.out.println(n);

}

 

//New way:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

list.forEach(n -> System.out.println(n));

 

-- Map reduce --

//Old way:

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);

intsum = 0;

for(Integer n : list) {

    intx = n * n;

    sum = sum + x;

}

System.out.println(sum);

 

//New way:

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);

intsum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();

System.out.println(sum);

 

** Note use of new Java8 Stream APIs. (see java.util.stream.Stream).

 

 

Comparator is a functional interface?

Above we used a lambda expression instead of a Comparator in the ArrayList.sort() method. In order for this to work, Comparator must be a functional interface. When I was looking through this I got hung up on why Comparator was a functional interface since a functional interface is defined as: “More precisely, a functional interface is defined as any interface that has exactly one abstract method.” However, if you look at the Comparator interface, you’ll see that it actually has two declared methods: compare() and equals().  To clear up any confusion – the explanation is: “The interface Comparator is functional although it explicitly declares two methods, because only one is abstract; equals is an explicit declaration of a concrete method inherited from Object that, without this declaration, would otherwise be implicitly declared.

 

 

There’s more that can be said about lambda expressions (specifically about lexical scoping and how ‘this’ is handled), but this email is getting too long so consider this just a primer J.

 -------------

 

In Java8, an anonymour inner class can access a non-final local variable, and this this applies to both anonymous inner classes and lambdas expressions. That’s because Java8 compiler does that for us automatically. That also makes lambda expressions easier to access the outer variable. However, as Jingwei mentioned, we can’t modify its value (or modify the reference of container type, but we can modify the contents in container, of course), it’s immutable.

分享到:
评论

相关推荐

    Harnessing the Power of Java 8 Lambda Expressions

    根据提供的文件信息,此文档是一本关于Java 8中Lambda表达式的书籍的一部分,具体书名为《Functional Programming in Java - Harnessing the Power of Java 8 Lambda Expressions》,作者是Venkat Subramaniam,出版...

    JAVA 8 Lambda表达式-Lambda Expressions.rar

    `JAVA 8 Lambda Expressions.pdf` 这份文档可能涵盖了以下主题: 1. Lambda 表达式的基本概念和语法 2. 函数式接口及其应用 3. Lambda 表达式与方法引用来实现函数式编程 4. Stream API 和 Lambda 表达式的结合使用...

    Lambda Expressions in Java 8 epub

    Lambda Expressions in Java 8 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    java 8 lambda- expressions 学习资料,例子。练习 java example

    Java 8是Java语言的一个重大版本更新,它引入了lambda表达式,这是Java平台的核心特性之一。Lambda表达式为Java带来了函数式编程的元素,使得开发者可以以更简洁的方式编写代码,尤其是在集合和多线程方面。本资料...

    Lambda Expressions in Java 8 azw3

    Lambda Expressions in Java 8 英文azw3 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    Lambda Expressions in Java 8 无水印pdf

    Lambda Expressions in Java 8 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者...

    Lambda Expressions in Java 8 mobi

    Lambda Expressions in Java 8 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    java8lambda表达式Demo

    Java 8 是一个重要的Java平台版本,因为它引入了许多新特性,其中最显著的就是Lambda表达式。Lambda表达式是函数式编程的关键元素,它允许我们以更简洁、更易读的方式编写代码,特别是在处理集合和并发任务时。在这...

    Java-8:Java8,lambda,流..

    Java 8 –简介Java 8 – Lambda表达式Java 8 –方法参考Java 8 –默认方法Java 8 –功能接口Java 8 –可选Java 8 –谓词Java 8 –日期时间Java 8 –流示例Java 8 –流独特Java 8 –流最大和最小Java 8 –流线Java 8...

    Java8的lambda表达式

    Java8的Lambda表达式是Java语言的一次重大更新,它引入了函数式编程的概念,极大地简化了处理匿名函数的方式,特别是在处理集合和并发操作时。Lambda表达式使得代码更加简洁、易读,同时也提升了程序的执行效率。在...

    Java Closures and Lambda(Apress,2015)

    These new changes make their debut in Java 8, and their highlight is the long-awaited support for lambda expressions in the Java language. You'll learn to write lambda expressions and use them to ...

    java8 lambda表达式学习总结

    Java 8 的 Lambda 表达式是其最显著的新特性之一,它引入了一种更为简洁、函数式的编程风格。Lambda 表达式使得处理匿名函数变得更加简单,尤其在需要定义短小、无状态的代码块时,它们可以极大提高代码的可读性和...

    Java 8新特性之Lambda与函数式编程.pdf

    Java 8引入了函数式接口的概念,这些接口只包含一个抽象方法,允许Lambda表达式的使用。Lambda表达式是一种简洁的表示匿名类的方法,它可以用于创建小型代码块,然后将其作为参数传递给方法或存储在变量中。类型推断...

    java8 Lambda 实践

    Java 8 的 Lambda 实践是 Java 语言的一个重要更新,引入了函数式编程的概念,极大地简化了处理集合和回调函数的方式。Lambda 表达式是这一特性的重要组成部分,它允许我们以更简洁、更易读的形式来表示匿名函数。...

    Java8的Lambda表达式

    Java 8引入了Lambda表达式,这是一种简洁的编写代码的方式,可以将代码块作为参数传递给方法,或者作为赋值给变量的对象。Lambda表达式为Java增加了函数式编程的能力,使代码更加简洁和灵活。在Java 8中,Lambda...

    英文原版-Lambda Expressions in Java 8 1st Edition

    In Java 8, a Lambda Expression is nothing but a block of code which can be passed around to execute. ,解压密码 share.weimo.info

    java8中的Lambda表达式

    Java 8 中的 Lambda 表达式是语言的重大更新,它引入了函数式编程的概念,使得代码更加简洁、易读。Lambda 表达式的主要目的是简化处理匿名内部类的情况,尤其是当这些类只需要一个方法时。 在传统的 Java 编程中,...

    Java8里面lambda的最佳实践Java开发Java经

    在Java 8中,Lambda表达式是一个重大更新,它为Java带来了函数式编程的特性,极大地简化了代码,特别是处理集合操作。以下是对Java 8 Lambda最佳实践的深入解析: 一、理解Lambda表达式基础 Lambda表达式是匿名函数...

Global site tag (gtag.js) - Google Analytics