Preliminary Exploration of Java8lambda expressions

Source: Internet
Author: User

Preliminary Exploration of Java8lambda expressions

Let's talk about the current fire. Let's look at functional programming. How nice javascript is to write. What about java? Everything is an object. It seems to be far away from functional programming, but in Java 8, we finally ushered in a lambda expression similar to functional programming-Java style. After refactoring your code with lambda, what do you think? Cool!

In this blog, let's take a look at the lambda expressions of Java 8 and learn about the lambda expressions!

Lambda expression syntax

Lambda statements can be expressed using the following pseudo code, which is very simple, but there are many simpler expressions,

(Type ...argument) -> {code}

There are also variants,

(Type... argument)-> x * y // execute x * y. If there is a returned value, the return value is automatically deduced here.
Preliminary Exploration of lambda expressions

Just look at the syntax is useless, the best learning method is to grasp it in practice. A few simple examples: Use lambda expressions to traverse a List. Before lambda is available, how do we traverse a List? I believe everyone is familiar with it,

    list = Arrays.asList(aaa, bbb, ccc);for(String item : list) {    System.out.println(item);}

Not to mention, let's see how lambda works,

    list = Arrays.asList(aaa, bbb, ccc);list.forEach((item) -> System.out.println(item));

One line of code! The key code is(item) -> System.out.println(item), We have already introduced this syntax above, because there is only one expression, so{}Can be omitted.
Wait, the above method is not the simplest,

    list = Arrays.asList(aaa, bbb, ccc);list.forEach(System.out::println);

What is this! Hey, System. out: println is equivalent(x) -> System.out.println(x). This syntax is described in detail below.

Similar to the traversal above, let's take a look at how the thread is written now,

new Thread(() -> {   // do something   System.out.println(hello thread);}).start();

Well, isn't it easy? It is also easy to understand with the above basics.

Sort! Sort!

Sorting in lambda is much simpler. Let's look at the following code,

String[] array = {bbb, ddd, aaa};Arrays.sort(array, (String a, String b) -> a.compareTo(b));

In Java 8, the Collection has another stream method. The stream method is inherently used with lambda. stream provides a lot of useful methods, such as filter for filtering. The following code, we only print strings starting with.

    list = Arrays.asList(abc, abb, ddd); item) -> item.startsWith(a))        .forEach(System.out::println);

Limit, similar to limit in SQL, is used to limit the number of traversal. For example, in the following code, we will traverse the first five pieces of data in the List,

    list = Arrays.asList(abc, abb, ddd, 111, ddd, yyy, 999);;

For more interesting Stream methods, go to the api to view the instructions. I will not explain them here.

Custom function interface

In the above Code, we all use functional interfaces provided by the system. Can we customize them? The answer is yes. to customize a function interface, you must meet the following two conditions.

This interface has only one method. Use annotation @ FunctionalInterface on the interface (not required, but a good programming specification is added)

Following the above specifications, let's customize a functional interface,

@FunctionalInterfaceinterface Func {    String builder(String firstName, String lastName);}

How can I use a function interface? In fact, you will already use it.

Func func = (String first, String last) -> { return first + . + last;};System.out.println(func.builder(f, l));

Well, I am too familiar with it, but some may have thought of more concise code,

Func func = (String first, String last) -> first + . + last;System.out.println(func.builder(f, l));
What are the two colons?

In the above example, we used System. out: println to say that System. out: println is equivalent(x) -> System.out.println(x). Now let's take a look at this::.
::Actually, it is a syntactic sugar that relies on lambda's automatic derivation (Nanni? Actually, lambda expressions are a syntactic sugar in java. I won't talk about conceptual things. Let's use three examples to learn.
Click this::Right.

class Util {    public static String getSomething(String a, String b) {        return a + ; + b;    }}@FunctionalInterfaceinterface Func {    public String get(String a, String b);}Func f = Util::getSomething;System.out.println(f.get(aaa, bbb));

The main code isFunc f = Util::getSomethingIn fact, he is equivalentFunc f = (String a, String b) -> Util.getSomething(a, b). Actually, Util. getSomething () is used to implement the get method of Func. However, it seems that there is a sense that Util has implemented the Func interface.
The above getSomething is a static method. What if it is an instance method?

class Util {    public String doGet(String a, String b) {        return a + ; + b;    }}Util util = new Util();Func f2 = util::doGet;System.out.println(f2.get(ccc, ddd));

That::And constructor?

class Student {    private String name;    public Student(String name) { = name;        System.out.println(;    }}@FunctionalInterfaceinterface StudentInterface {    Student build(String name);}StudentInterface si = Student::new;Student stu =;


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.