Java 9 has already been released to the public, but this article is for those who want to review the lambda expressions added in Java 8 again. It also serves as a personal summary. I would appreciate it if you could point out any mistakes!
The big thing that changed in Java 8 is lambda expressions. Originally, in mathematics, there was an idea that "functions are treated like variables and operated", and the name λ (lambda) is often used as the variable. Java's lambda expression incorporates this mathematical idea into Java, and I think it's easy to understand that the meaning is "expression of a function that can be treated as a value".
For example, the following code.
(p) -> (p.getAge()) < 30)
This is an expression that returns if the age of p is less than 30 when p is put in the function.
Let's understand the lambda expression by writing a sample lambda expression and decomposing the code.
LambdaSample.java
public class LambdaSample {
public static void main(String[] args) {
Runnable r = () -> System.out.println("Hello Lambda!");
r.run();
}
}
When I run the above example, I get the following result.
hello lambda!
The code written in a lambda expression is below.
() -> System.out.println("Hello Lambda!")
If you write this LambdaSample.java before JDK8, it will be as follows.
RunnableSample.java
public class RunnableSample {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Before Lambda!");
}
};
r.run();
}
}
In LambdaSample.java, the following part is replaced with a lambda expression.
JDK8 or earlier
new Runnable() {
@Override
public void run() {
System.out.println("Before Lambda!");
}
}
JDK8
() -> System.out.println("Hello Lambda!")
The amount of code has decreased considerably.
This code written before JDK8 is also called "anonymous class". In other words, a lambda expression can be said to be "a rewrite of an anonymous class object that implements an interface."
http://java-code.jp/106 https://qiita.com/sanotyan1202/items/64593e8e981e8d6439d3 ["Lambda expression" starting with Java8](https://www.amazon.co.jp/Java8%E3%81%A7%E3%81%AF%E3%81%98%E3%82%81%E3%82 % 8B% E3% 80% 8C% E3% 83% A9% E3% 83% A0% E3% 83% 80% E5% BC% 8F% E3% 80% 8D-I% E3% 83% BB-BOOKS-% E6% B8% 85% E6% B0% B4-% E7% BE% 8E% E6% A8% B9 / dp / 4777518418 / ref = sr_1_2? ie = UTF8 & qid = 1508761078 & sr = 8-2 & keywords = java8) [Java SE 8 Practical Programming that Java Programmers Want to Learn](https://www.amazon.co.jp/Java%E3%83%97%E3%83%AD%E3%82%B0%E3% 83% A9% E3% 83% 9E% E3% 83% BC% E3% 81% AA% E3% 82% 89% E7% BF% 92% E5% BE% 97% E3% 81% 97% E3% 81% A6% E3% 81% 8A% E3% 81% 8D% E3% 81% 9F% E3% 81% 84-Java-SE-8-% E5% AE% 9F% E8% B7% B5% E3% 83% 97 % E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82% B0-ebook / dp / B00VM0FMIW / ref = sr_1_3? Ie = UTF8 & qid = 1508761078 & sr = 8-3 & keywords = java8)
Recommended Posts