Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

FizzBuzz in Java 8  RSS feed

 
Gordon Brown
Ranch Hand
Posts: 58
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been getting to grips with Java 8 of late, and clearly I was rather bored today...

Any suggested improvements on the following? I'm guessing some would object to the higher order function (due to the verbosity of not just using the modulus operator directly).

Any feedback appreciated.

 
Campbell Ritchie
Sheriff
Posts: 55298
156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice.

But surely the isFactorOf method should be called isMultipleOf?
 
Gordon Brown
Ranch Hand
Posts: 58
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hahaha... doh! Brain fart. Yes it should.

Thanks.
 
Rob Spoor
Sheriff
Posts: 21044
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no need for the method to return an IntPredicate - a simple boolean would do. And getWordForNum could also return a String and include the call to Integer.toString.
 
Gordon Brown
Ranch Hand
Posts: 58
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob,

The isMultipleOf method can't return a boolean: It needs to return a function that takes an int (the number we're testing against) and returns a function that takes an int and returns a boolean (i.e. an IntPredicate). If you were to go down the route of having a method that returned a boolean, you'd need to have both isMultipleOf3(int num) and isMultipleOf5(int num), which isn't nearly so nice.

You're right about the String... I'm essentially performing the check twice. I think I was too keen to work in Optional.

Below is an updated version based on the above.

 
Rob Spoor
Sheriff
Posts: 21044
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or just pass two arguments to the method:
 
Gordon Brown
Ranch Hand
Posts: 58
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nah... too simple

You're right, of course. Think I've been too keen to use my new hammer, and everything looks like a nail.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!