Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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: 27211
87
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: 4187
57
  • 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.  
 
What's wrong? Where are you going? Stop! Read this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic