2

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

4
  • Seems like there is no element that is empty("") Commented Dec 30, 2019 at 15:51
  • 6
    Sorry but what you are doing looks like misuse of Optional. If you know that some value exists (regardless if it is correct or not, as long as it is not null) then Optional isn't right tool. Such cases should are better suited to be handled by simple if(validate(value)){..handle correct value..} else {..handle incorrect value..}. For now your question looks like XY problem Commented Dec 30, 2019 at 16:20
  • What if your input is not empty what is the expected result? Commented Dec 30, 2019 at 16:29
  • @YCF_L the original value Commented Dec 30, 2019 at 16:31

3 Answers 3

6

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); 
Sign up to request clarification or add additional context in comments.

8 Comments

did not get u , u mean to use it inside filter , String l3 = l > 0 ? l.toString() : "Invalid";
@coder25 no, you don't need to use Optional no filter just like it is.
@coder25 but why is it there in the first place? Why involve Optional if your goal (based on how your question looks like now, not sure if it is your real goal) can be achieved in simpler way shown in above answer?
@coder25 please show us the original problem, don't post an XY problem
@coder25 Sorry but I don't follow. It is like saying "it is there because it is there" which doesn't give us much. Usually things are in some place because someone made decision that it should be there, and I am asking for reasons behind that decision (why someone - author of code, which is probably you - though that Optional must be used in that place?).
|
4

If you're on Java 9+, you can use or, which takes an alternative Optional if the present one is empty:

Optional<String> l3 = l2.filter(String::isEmpty) .or(() -> Optional.of("invalid")); 

1 Comment

thanks. In case I do not need Optional need to print Invalid value +l2 , orElse wont work.Any idea how we can achieve
1

How about not using filter.

String l3 = l2 .map(Object::toString) .orElse("invalid"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.