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
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);
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