• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Writing fully optional and functional method that maps String to natural number

 
Ranch Hand
Posts: 47
IntelliJ IDE Python Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm trying to write fully functional and optional method that maps optional String -> optional natural number (let suppose natural numbers begin with 0)
This is what I wrote so far:



However my intuition tells me that it is possible to write this function with using only interfaces from Functional library instead using if statements.
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm sure you're right. My rough idea goes like this:

Apply .stream() to the Optional<String> and you'll get a Stream<String> with 0 or 1 entries. You can use filter() instead of your if-statement, that's what filter() is for, then you need some kind of map() to convert a String to an int if you have one, then you need to make the result into an Optional. Give it a try.
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Andrzej, your intuition is correct.  Optional has map() and filter() methods - both of these are designed to do nothing on an empty Optional.  So you don't have to check isPresent() before calling these methods - they will do that for you, internally.

Converting to stream() is unnecessary since Optional already has the needed methods.  
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic