Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
  • Piet Souris
  • Frits Walraven
  • Carey Brown

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

Ranch Hand
Posts: 35
IntelliJ IDE Python Linux
  • Mark post as helpful
  • send pies
  • 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.
Posts: 25682
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • 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.
Posts: 3571
  • Mark post as helpful
  • send pies
  • 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.  
Onion rings are vegetable donuts. Taste this tiny ad:
Thread Boost feature
    Bookmark Topic Watch Topic
  • New Topic