• Post Reply Bookmark Topic Watch Topic
  • New Topic

Results of using Optional<> map function  RSS feed

 
Roy Pozarelli
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question about the code below. Why is added.toString() showing Optional[false] when the result of this is adding to the results set? I didn't expect this value. In reading the documentation for Optional's map()
"If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional." and the return value of the add on a Set is boolean of true if this set did not already contain the specified element.

I was expecting the output to show
added : Optional[true]



added : Optional[false]
results.isEmpty : false

So what am I missing?
 
Pierre-Yves Saumont
Author
Ranch Hand
Posts: 98
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because add is a function returning true if the object was added and false otherwise. As you add twice the the same object, the second call to add returns false. Try this:



 
Roy Pozarelli
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, my bad, copied one too many lines.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!