-1

Which is faster stream or for each loop and why? which should be used in which scenario?

import java.util.*;

public class Ran {

    public static void main(String[] args) {

        // Get and shuffle the list of arguments
        List<String> argList = Arrays.asList(args);
        Collections.shuffle(argList);

        // Print out the elements using JDK 8 Streams
        argList.stream()
        .forEach(e->System.out.format("%s ",e));

        // Print out the elements using for-each
        for (String arg: argList) {
            System.out.format("%s ", arg);
        }

        System.out.println();
    }
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126

1 Answers1

0

I'd expect the stream version to be slighter slower as it involves more work but by what margin this is you'll really need to measure.

Unless performance is really really important to you I wouldn't worry about it but instead go with the approach that most expresses your needs and that you find most readable.

FYI, argList.stream().forEach(...) can be simplied to argList.forEach(...)

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126