Deep understanding of Lambda expressions

1、 Background

Lambda expressions in Java 8 are no longer "new features".

Now many people use lambda expressions in their work.

However, do you really understand the underlying principle of Lambda expressions?

2、 Analysis

The following is a very simple code that uses Stream.

We use the Jclasslib plug-in (described in "IDEA Plug-ins Who Meet Later") to check the bytecode.

You can also use javac and javap instructions to execute on the command line.

For example:

javac ListDemo.java

javap -p -s -c -v -l ListDemo

We can see one more internal class and BootstrapMethods

lambda$main$0

0 aload_ 0

1 ldc #20

3 invokevirtual #21

6 ireturn

amount to:

private static boolean lambda$main$0(String name){

return name.startsWith("tom");

}

lambda$main$1

0 aload_ 0

1 invokevirtual #19

4 areturn

amount to

private static String lambda$main$1(String name){

return name.toLowerCase();

}

From the above simple analysis, we can see that lambda expressions will ultimately be compiled as private static methods.

Perform dynamic method calls through the invokedynamic instruction.

as

50 invokedynamic #10

From the JVM document, we can see that this method is used to realize dynamic call calculation. It is converted into dynamic calculation call through constant pool key amount symbol reference, where CallSite instance is the target method call instance.

You can always follow it in the plug-in

# 10 in the constant pool in invokedynamic # 10 is the following:

Where BootstrapMethods # 0 corresponds to

You can see that this is a call to java. lang.invoke. LambdaMetafactory # metafactory. The return value is the java. lang.invoke. CallSite object, which represents the actual target method call.

3、 Expansion

With the above explanation, I believe you have a deeper understanding of Lambda expression.

Please guess and verify the underlying implementation of Map.forEach?

Please write your own logical equivalent code.

I hope you can see the Lambda expression, and then you can make up for the ability of the underlying implementation.

4、 Summary

A lot of knowledge seems to be taken for granted, but we can continue to dig deeper and learn different knowledge.

Only when you really understand a knowledge point can you have enough confidence in the interview.

In addition, Lambda is good, but don't be greedy. Abusing lambda will challenge the readability and maintainability of the code.

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us