Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java 8 streams - Filter if else not  RSS feed

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm trying to figure out if there's a more elegant way of doing this with streams rather than checking separately through an if-else statement? How would you rewrite this code? Thanks in advance!

 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I may be missing something here, but it seems to me that wrapping the possibly null parameter in an Optional isn't required.(typed and copy/pasted from your code here, so may have missing parentheses or other typos)

((corrected one typo a minute after posting))
 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks super elegant! Thanks! I thought I should always wrap nullables with Optional. Would you have any opinions on that?
 
Stephan van Hulst
Saloon Keeper
Posts: 7003
110
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously not if it leads to less clear code. Don't be dogmatic about guidelines.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15865
81
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Scala I would try to avoid null as much as possible, and always use Option instead. In Scala, null really only exists for interoperability with Java.

But in Java, the use of null has been so much part of the way things are normally done that I wouldn't do it in the same was as in Scala.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!