Converting iteration loop body into functional code Java 8

arabian_albert :

I want to convert the below imperative code into functional code using Java 8.

The way it works is I capture the current time before and after the API call, then I subtract the before from the after. The result is a rough time it took for the API to execute, I also cature memory usage. I gather this response times and memory usage data into 2 lists which I then process.

So how to maintain the current fucntionality while converting into functional code?

Simulator simulator = new Simulator();

List<Double> execTimes = new ArrayList<>();
List<Long> execMemory = new ArrayList<>();

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 1000; i++)
{
    Runtime runtime = Runtime.getRuntime();
    runtime.gc();

    Long startTime = System.currentTimeMillis();

    byte[] dataBytes = simulator.generateData(simulator.readFileAsString(input)); // API to measure

    long memoryUsed = runtime.totalMemory() - runtime.freeMemory(); // capture memory usage
    Long stopTime = System.currentTimeMillis();
    Long time = stopTime - startTime; // measure api response time

    sb.append(i).append(',').append(time)
      .append(',').append(memoryUsed).append(',').append("\n");


    simulator.writeToFile(new File(inputDoc), dataBytes, i);

    execMemory.add(memoryUsed);
    execTimes.add(time.doubleValue());

    System.out.println("Execution time (MS): "+(time));
    System.out.println("Memory usage (B) ["+i+"]: "+memoryUsed);
}

This doesn't really work:

IntStream.range(0, 1000)
                    .forEach(i ->
                            simulator.generateData(simulator.readFileAsString(inputDoc)) );

I tried using the range but I'm not sure if this is the proper use case for Integer Stream since it does not allow for other embellishments like caturing response times. Perhaps a monad would work here?

Ousmane D. :

This is not a good example to use the so-called "functional programming" features as of JDK8. There are too many side effects and different things going on.

one thing you could do is use IntStream.range for the loop:

IntStream.range(0, 1000).forEach(index -> {
   // logic here          
});

but I wouldn't recommend this, your approach seems just fine.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132320&siteId=1