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?
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 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.
FunctionalIf func = num -> { return num +" * 2 = " + num*2;};
Since it has one argument, num
can be inferred to be of type int.
FunctionalIf func = num -> num +" * 2 = " + num*2;
Since it is a simple sentence, the result of the sentence can be inferred as output.
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
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.
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).
You can't use a single _
in the variable name of a lambda expression argument.
Recommended Posts