Recently, I was blessed with the opportunity to use Java because of my work. I updated my ancient Java (1.3) knowledge.
This is a function to easily implement a functional interface.
This alone is refreshing, so I would like to explain it with an example.
public static void main(String[] args) {
class Sample implements Runnable {
public void run() {
System.out.println("I Love Pengin!");
}
}
Runnable runner = new Sample();
times( 10, runner );
}
public static void times( int count, Runnable runner ) {
for( int i = 0; i < count; i++ ) {
runner.run();
}
}
public static void main(String[] args) {
funcCall( 10, () -> System.out.println("I Love Pengin!") );
}
public static void times( int count, Runnable runner ) {
for( int i = 0; i < count; i++ ) {
runner.run();
}
}
The example is the processing to the times
function that repeats the specified processing multiple times.
If you compare them, you can see that the lambda expression is quite complete.
The method of substituting a part of the processing with another object is called delegation. By using a lambda expression, I think the advantage is that this delegation is much easier to write.
Let's look at the format when using a lambda expression
() -> System.out.println("I Love Pengin!")
()
represents the method argument. We don't use arguments this time, but you can use them.->
describes the actual processing content. If the processing content spans multiple processes, write -> {Processing}
here.By specifying the argument of the lambda expression, the argument can be used during processing.
(i) -> System.out.println("I Love Pengin!" + i)
It is necessary to use the function interface properly according to the type of argument and return value to be used. If there is one argument and no return value, it will be as follows.
public static void times( int count, Consumer<Integer> runner ) {
for( int i = 0; i < count; i++ ) {
runner.accept(new Integer(i));
}
}
The interface to use properly is as follows.
type | Function interface | Method |
---|---|---|
0 arguments that do not return a value | Runnable | run |
1 argument that returns no value | Consumer | accept |
2 arguments that do not return a value | BiConsumer | accept |
0 arguments that return a value | Supplier | get |
1 argument that returns a value | Function | apply |
2 arguments that return a value | BiFunction | apply |
1 argument that returns a boolean value | Predicate | test |
Two arguments that return a boolean value | BiPredicate | test |
1 argument that returns the operation result | UnaryOperator | test |
2 arguments that return the operation result | BinaryOperator | test |
Recommended Posts