For example:
private String test(Optional myOptional)
{
myOptional.ifPresent(() -> return "1");
return "0";
}
so when I call test(myOptional) it will return "1";
For example:
private String test(Optional myOptional)
{
myOptional.ifPresent(() -> return "1");
return "0";
}
so when I call test(myOptional) it will return "1";
You can't "break" out of the lambda body and return a value from the enclosing method. The return
used in the lambda works only in the scope of the lambda body.
The idiomatic way would be to levarage Optional
API properly:
private String test(Optional<Object> myOptional) {
return myOptional
.map(s -> "1")
.orElse("0");
}
Also, keep in mind that Optional
s should not be used as a method argument:
private <T> String test(Optional<T> myOptional)
–
Marya The issue you're having is that the return
is taken as the return of the lambda function, not the return of the 'test' function.
Optional.ifPresent
is not expecting to be given a function that returns a value. It expects a Consumer<T>
which is effectively a function which takes exactly one parameter and returns nothing. As a normal function, rather than a lambda it would look something like this:
void myConsumer(String s)
{
System.out.println(s);
}
You probably want to use isPresent
('is' not 'if'):
if (myOptional.isPresent())
{
return "1";
}
else
{
return "0";
}
or using a ternary operator:
return myOptional.isPresent() ? "1" : "0";
As an aside, you are using the raw type of Optional
. This will result in a compiler warning. You should declare what type the Optional
will hold by using generics:
Optional<String> myOptional = /*something*/;
This will give you compile-time type safety that the Optional
won't hold values other than strings.
Use Atomic classes, which allows define value
public void executeAction(final Consumer<EntityManager> action) {
//Any code
}
final AtomicInteger rowsDeleted = new AtomicInteger();
jpaManager.executeAction((aux) -> {
rowsDeleted.set(aux.createQuery(delete).executeUpdate());
});
return rowsDeleted.get();
© 2022 - 2024 — McMap. All rights reserved.
Function
. Does that fit your need? You would calltest().apply()
– BlowtubemyOptional.map(item -> "1").orElse("0")
. Maybe you should consider another example – Brnabaaccept
it – Antenatal