Today I met part of weird code which I do not understand.
What can mean something like this ()-> for example
method( ()-> System.out.println("Hello") );
another question is, what is an output of String:
[AB][CD]*EF+(X/Y)
of course there were not any instance of A, B etc.But I there were answers like
ABCDEFX, ACEFXX, ACEFXA,
I do not remember them
Can anybody help me?
Suppose you have an interface that declares one method:
public static interface MyFunctionalInterface {
void m1();
}
And you have a method that receives an object of that type as a parameter:
public void method(MyFunctionalInterface i) { ... }
You can implement that interface and use it immediately using anonymous inner classes like this:
method( new MyFunctionalInterface() {
public void m1() {
System.out.println("Hello");
}
});
In Java 8 you can replace that with a lambda expression such as the one you showed:
method( () -> System.out.println("Hello"); );
The empty parameters represent the m1() method, with no parameters.
Suppose the functional interface you were using had a method with one parameter (if your method had the form method2(ActionListener s) { ... } for example), then you would use:
method2( e -> System.out.println("Hello"); );
which would be the same as doing this:
method2( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
There are many tutorials about Lambda expressions in Java 8. This one is a good quick-start.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With