【问题标题】:Java 8 stream and foreach loop [duplicate]Java 8流和foreach循环[重复]
【发布时间】:2018-11-19 19:06:18
【问题描述】:

哪个是更快的流或每个循环,为什么?应该在什么场景下使用?

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();
    }
}

【问题讨论】:

  • 流可能比较慢。

标签: java java-8 java-stream


【解决方案1】:

我希望流版本会稍微慢一些,因为它涉及更多的工作,但是你真的需要测量多少余量。

除非性能对您真的 真的很重要,否则我不会担心它,而是采用最能表达您的需求并且您认为最易读的方法。

仅供参考,argList.stream().forEach(...) 可以简化为 argList.forEach(...)

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 1970-01-01
    • 2014-07-22
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多