I will explain the description of lambda expressions introduced from Java 8 for beginners with a memorandum.
Lambda expressions are a description format introduced from Java8 that allows methods to be treated like variables. Lambda expressions can simplify your writing and make your code easier to read.
Also, using a lambda expression when using a functional interface such as the Stream API makes it very easy to write! !!
First of all, I will explain the actual description method of the lambda expression.
RunnableLamda.java
public static void main(String[] args) {
Runnable runner = () -> System.out.println("Hello");
runner.run(); //Hello
}
The above describes the runnable interface using a lambda expression. The anonymous class is abbreviated with "new Runnabl () {}" and "public void run".
Also note that lambda expressions can only use one interface with abstract methods.
The argument type is automatically estimated by the compiler and does not need to be described. However, even if you write the type as usual, you will not get a compile error.
StreamAPI Like the lambda expression, the function "Stream API" added in Java 8 is a convenient API when processing a set of elements such as List and Collection.
The Stream API is built on the premise of lambda expressions, so it's very compatible.
For example, the process of displaying only even numbers in 1 to 6 can be written as follows.
StreamLamda.java
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6);
integerList.stream()
.filter(i -> i % 2 == 0)
.forEach(i -> System.out.println(i));
We will also introduce other Stream APIs. forEach Loop the contents of the List. Very easy to write.
ForEachSample.java
Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6 }).forEach(System.out::println);
filter It is an intermediate operation for filtering and serves as an if statement. Pass a lambda expression that is T-> boolean as an argument. Collect only elements whose expression is true.
FilterSample.java
Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6 }).stream().filter(x -> x > 3).forEach(System.out::println);
map It is an intermediate operation that can convert elements, and you can perform four arithmetic operations on elements and even convert types.
MapSample.java
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6);
integerList.stream()
.map(i -> "The element is" + i + "is")
.forEach(i -> System.out.println(i));
The lambda expression and Stream API introduced this time can also be written in the conventional way. However, in the development field, there are many opportunities to read code written by others as well as coding by yourself. Others' programs may contain lambda expressions and Stream APIs, so get used to them!
Recommended Posts