Java8 to start now ~ forEach and lambda expression ~

Java 9 has also been released, but I'm still not sure about Java 8, so I'll summarize it.

forEach() In Java8, the forEach () method has been added to List, Map, arrays, etc. Before Java 7

for(String s : list) {
	System.out.println(s);
}

And the process that used 3 lines

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

You can now write in one line.

Why can I write it like this?

Functional interface

In Java8, an interface that has only one abstract method is called a functional interface and can be passed as a lambda expression.

FunctionalIf.java


@FunctionalInterface
public interface FunctionalIf {

	public String retStr(int number);
}

However, the following methods may be included -Static method -Default method -Override of public method of java.lang.Object (toString () and equals ())

Annotating the @FunctionalInterface will result in a compile error when the conditions are not met, but it is not required.

Lambda expression

Lambda expressions are grammars introduced in Java 8. You can implement a functional interface with the following syntax

(Arguments of the method to implement) -> {processing}
FunctionalIf func = (int num) -> { return num +" * 2 = " + num*2;};

This alone is pretty concise, but it can be omitted further.

Type and () can be omitted if the method to be implemented has one argument

FunctionalIf func = num -> { return num +" * 2 = " + num*2;};

Since it has one argument, num can be inferred to be of type int.

If the process is a simple sentence, return and {} can be omitted

FunctionalIf func = num -> num +" * 2 = " + num*2;

Since it is a simple sentence, the result of the sentence can be inferred as output.

Use of lambda expression

I ended up with this format

//Implement a functional interface with a lambda expression
FunctionalIf func = num -> num +" * 2 = " + num*2;

//Use the implemented method
System.out.println(func.retStr(1));
System.out.println(func.retStr(2));

Execution result


1 * 2 = 2
2 * 2 = 4

ForEach () again

The forEach () method in Java 8 can be used in a class that implements the Iterable interface method default void forEach (Consumer <? Super T> action). https://docs.oracle.com/javase/jp/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-

The argument Consumer is a functional interface with void accept (T t) (receives some arguments and returns no values). https://docs.oracle.com/javase/jp/8/docs/api/java/util/function/Consumer.html

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

So, you passed the implementation of Consumer as an argument of the forEach () method in a lambda expression.

Precautions when using lambda expression

Variable scope

Variables declared outside the lambda expression can be referenced inside the lambda expression. However, it cannot be changed.

String str = " item";
list.forEach(s -> {
  System.out.println(s + str); //Can be referenced
  // str = " changed";  //Change is NG
});

Also, variables declared outside the lambda expression cannot be used for variable argument names (a compilation error will occur).

Variable name restrictions

You can't use a single _ in the variable name of a lambda expression argument.

Recommended Posts

Java8 to start now ~ forEach and lambda expression ~
Java8 to start now ~ Optional ~
Java 8 ~ Stream API ~ to start now
[Java] Lambda expression
Java lambda expression
Now let's recap the Java lambda expression
Java 8 to start now ~ Date time API ~
java neutral lambda expression 1
Java 8 lambda expression Feature
java lambda expression memo
Java lambda expression [memo]
Introduction to lambda expression
Studying Java 8 (lambda expression)
I want to ForEach an array with a Lambda expression in Java
Review java8 ~ Lambda expression ~
Java lambda expression again
[Java] Functional interface / lambda expression
Java8 stream, lambda expression summary
[Java] Introduction to lambda expressions
[Introduction to Java] About lambda expressions
Java, interface to start from beginner
What is a lambda expression (Java)
Java, arrays to start with beginners
I tried to summarize Java 8 now
How to use Java lambda expressions
I tried to summarize Java lambda expressions
Nowadays Java lambda expressions and Stream API
Java implementation to create and solve mazes
[Java] for Each and sorted in Lambda
[Java] How to output and write files!
AWS Lambda with Java starting now Part 1
[Introduction to Java] Variable declarations and types
Note: [Docker] How to start and stop
Java to C and C to Java in Android Studio
Transform from a normal class to a lambda expression
[Java] How to use FileReader class and BufferedReader class
Two ways to start a thread in Java + @
Java switch statement and break, Kotlin when expression ...
[Java] How to get and output standard input
[Java] Summary of how to abbreviate lambda expressions
Try to link Ruby and Java with Dapr
Java upload and download notes to Azure storage
I want to use java8 forEach with index
Effective Java 3rd Edition Chapter 7 Lambda and Streams
How to get and study java SE8 Gold
How to solve an Expression Problem in Java
How to access Java Private methods and fields
Java8 Lambda expression & Stream design pattern reconsideration --Command pattern -
[Java] How to use Calendar class and Date class
Pass the condition to be used in the Java8 lambda expression filter () as a parameter
[Java] forEach method
Java and JavaScript
Hello Java Lambda
Introduction to java
Features that are likely to enter Java 10 for now
Convert Java enum enums and JSON to and from Jackson
[Java] Types of comments and how to write them
[Java Silver] Summary of points related to lambda expressions
[Java] Sort the list using streams and lambda expressions
[In-house study session] Java basics-Lambda expression and Stream API- (2017/07/13)
[Java] Convert character strings to uppercase / lowercase (AOJ⑨-swap uppercase and lowercase)