This question already has answers here:
What does the arrow operator, '->', do in Java?
(6 answers)
Closed last year.
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.
Related
This question already has answers here:
Java 8 method reference unhandled exception
(6 answers)
Closed 1 year ago.
I have two functions throwing Exception:
public void foo() throws Exception {
// something
}
public void bar() throws Exception {
// something
}
If I combine those function calls using curly braces in lambda expression, it needs try/catch to handle exception.
public void someFunction() throws Exception {
someList.forEach(e -> {
// Show compile error and need try/catch
foo();
bar();
});
}
However, if I combine in for-loop, it is fine.
public void someFunction() throws Exception {
for (SomeElement e : someList) {
foo();
bar();
}
}
I though try/catch needed because of new closure created (using bracket), but in for-loop, it does not require.
I solved it by just using for loop, but I wonder why it happens.
List#forEach expects a Consumer.
Consumer is a (single-abstract-method) interface that looks like this (simplified):
#FunctionalInterface
public interface Consumer<T>{
void accept(T t);
}
As you see, accept does not throw any checked exceptions.
The lambda expression is an implementation of that interface so it cannot throw any exceptions, no matter what the other code does.
I have this construction:
if (Objects.isNull(user.getMartialStatus())) {
user.setMartialStatus(MartialStatus.MARRIED);
}
I have many of them, & I want to optimize code using functional interface.
Okay. I write something like this:
public static <T> void processIfNull(T o, Supplier<Void> s) {
if (Objects.isNull(o)) {
s.get();
}
}
Then, I wait that this code shall work:
processIfNull(user.getMartialStatus(), () -> user.setMartialStatus(MartialStatus.MARRIED));
But IDEA write:
void is not compatible with Void
Please, tell me, what to do.
As the error explains Void is a class which is not equivalent to void. Supplier<Void> expects to return Void like Supplier<String> will expect String object to return.
So your functional interface should be like below.
It has a void apply() which matches the signature of () -> ...
#FunctionalInterface
public interface ActionIfNotNull {
void apply();
}
However when you search for an inbuild functional interface, you can come up with Runnable as Jon Skeet suggested.
Solution
public static <T> void processIfNull(T o, Runnable s) { // instead of you Runnable can use your own functional interface like ActionIfNotNull
if (Objects.isNull(o)) {
s.run();
}
}
As of Java 9 Optional has the ifPresentOrElse method, which could be used for this.
Optional
.ofNullable(user.getMartialStatus())
.ifPresentOrElse(o -> {}, () -> user.setMartialStatus(MartialStatus.MARRIED););
You could also replace the o -> {} by some NOOP Consumer if you like, like this:
private static final Consumer<Object> NOOP = o -> {};
...
Optional
.ofNullable(user.getMartialStatus())
.ifPresentOrElse(NOOP, () -> user.setMartialStatus(MartialStatus.MARRIED););
Anyway, I think the solution Trine came up with, is preferable, because it makes it much clearer, what's going on.
This question already has answers here:
scope resolution operator without a scope
(6 answers)
Closed 8 years ago.
There is one line of C++ code shown below.
return ::as_Register(value() >> 1);
I just want to know what's the meaning of the '::' which has nothing before it.
Is it the C++ syntax? Can there be nothing before '::'? Such as return ::myMalloc(size)?
The code is from jdk8 openjdk/hotspot/src/cpu/x86/vm/vmreg_x86.inline.hpp.
I am deeply studying the JDK.
A :: references the global namespace:
void bar();
namespace some_namespace
{
void bar();
void foo()
{
// writing bar() would call some_namespace::bar()
// but if we want to call the global bar() we have to write:
::bar();
}
}
It's C++. It means that you import this function from other namespaces.
Example:
namespace foo {
void bar();
}
void bar();
namespace foo {
void foobar()
{
bar(); // Means foo::bar()
::bar(); // Means bar() outside foo namespace
}
}
This question already has answers here:
Calling overloaded functions with "null" reference
(2 answers)
Closed 8 years ago.
I am new learner of Java. I am trying to understand the concept of passing argument in function and function overloading. I found few example on a java web site which where following code is given, my doubt is if null is passed to nh() then how "string" is displayed in output. Here is the code
public class CLI_APP
{
public static void main(String[] args)
{
jh(null);
}
public static void jh(String s)
{
System.out.print("String");
}
public static void jh(Object o)
{
System.out.print("Object");
}
}
In same code if below lines are added
public static void jh(Integer s)
{
System.out.print("Integer");
}
I got an compilation error of
"Method is ambiguous"
WHY this happen?
my doubt is if null is passed to nh() then how "string" is displayed in output
Overloaded methods are matched from bottom to top level of classes. Object class sits at the top level so it will be matched at the last. Having said that, null is first match to the String parameter method and a String can be null so this method is called.
If you also add the following method
public static void jh(Integer s)
to your code then jh(null) call introduces the ambiguity between Integer and String as both can be null.
Lean more here : Java Language Specification: Choosing the Most Specific Method
Integer and String both support null , so it generate ambiguity error at compile time,
Now, if you use int instead of Integer then it will work because int not support null.
public class testJava {
public static void main(String[] args)
{
jh(null);
}
public static void jh(String s)
{
System.out.print("String");
}
public static void jh(Object o)
{
System.out.print("Object");
}
public static void jh(int o)
{
System.out.print("Object int");
}
}
Java always use the most specific method. In your first example it will print "String" instead of "Object" because String is more specific than Object.
In your second example, java canĀ“t choose if null is better for Integer or String. You should cast your call or use primitives to remove your ambiguity.
This would work:
public static void jh(int s)
{
System.out.print("Integer");
}
Also this would work:
jh((String) null);
This question already has answers here:
Using an arbitrarily defined method of an anonymous interface
(4 answers)
Closed 9 years ago.
I can imagine some very creative code in Java:
Object thing = new Object() {
public void speak() {
System.out.println("Hi!");
}
};
thing.speak();
Or even, to get the full closure effect, define a Function interface ... you get the idea?
Why doesn't this code work?
i believe you can do it like this :-
new Object() {
public void speak() {
System.out.println("Hi!");
}
}.speak();
may help you .
Not sure about the usefulness in this example, but some type of overriding method(s) on the original declaration is useful and because of it is overriding, you can call the methods. Otherwise in your case, just use the reflection as:
thing.getClass().getMethod("speak").invoke(thing);
and for the overriding method:
Object thing = new Object() {
public void toString() {
System.out.println("Hi! Me inside your mind!");
return "not today!";
}
};
thing.toString();