Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter Optional.empty in java 8

I want to filter the values with 0 to print message invalid but I get Optional.empty as result

 Long l = 0L;
 Optional<String> l2 = Optional.of(l).filter(t -> t>0).map(t ->t.toString());
 Optional<String>l3 =l2.filter(String::isEmpty).map(t ->"invalid");
 System.out.println(l3);

Need return type to be Optional<String>

Expected output - Invalid
Actual Output - Optional.empty

Updated

Need return type to be String

Expected output - Invalid value 0
Actual Output - Optional.empty

like image 774
coder25 Avatar asked Mar 20 '26 06:03

coder25


1 Answers

No need to use Optional or filter, all you need is just :

String l3 = l > 0 ? l.toString() : "Invalid";

If you want to handle the null then :

String l3 = (l != null && l > 0) ? l.toString() : "Invalid";

If you want to show the number in the Invalid case, then :

String l3 = (l != null && l > 0) ? l.toString() : String.format("Invalid %d", l);
like image 104
YCF_L Avatar answered Mar 21 '26 21:03

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!