Skip to content
Advertisement

Convert iterative method to functional with Java 8 Streams

I have this algorithm right here,

JavaScript

that gives me the cubic root of n with a loss precision of e. I need to do the same thing but using Java 8 Streams. Math2 is from a private git rep. You can use Math.pow instead; it will work too. How can I do the same algorithm with Streams?

Advertisement

Answer

Java Stream API has method Stream::iterate starting from Java 9, therefore a class representing the iteration steps/states may be implemented as follows:

JavaScript

Then the stream-based solution looks like this:

  1. define an initial seed with start, end, n
  2. use Stream::iterate with hasNext predicate to create a finite stream 2a) or use older Stream::iterate without hasNext but with Stream::takeWhile operation to conditionally limit the stream – also available since Java 9
  3. use Stream::reduce to get the last element of the stream
JavaScript

Output:

JavaScript

In Java 11 static Predicate::not was added, so the 2a solution using takeWhile could look like this:

JavaScript

Output (for EPS = 1E-12):

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement