【问题标题】:Arrays.stream(array) vs Arrays.asList(array).stream()Arrays.stream(array) 与 Arrays.asList(array).stream()
【发布时间】:2016-09-12 03:46:35
【问题描述】:

this 问题中已经回答了两个表达式相等,但在这种情况下它们会产生不同的结果。对于给定的int[] scores,为什么会这样:

Arrays.stream(scores)
        .forEach(System.out::println);

...但这不是:

Arrays.asList(scores).stream()
        .forEach(System.out::println);

据我所知.stream() 可以在任何集合上调用,列表肯定是。第二个代码 sn-p 只返回一个包含整个数组而不是元素的流。

【问题讨论】:

    标签: java arrays foreach java-8 java-stream


    【解决方案1】:

    Arrays.asList 需要 Object 数组而不是 primitives 数组。 它不会抱怨编译时间,因为原始数组是一个对象。

    它可以将一个对象作为列表,但对象(原始数组是一个对象)里面的内容不能转换为列表。

    原始数组可以转换为流使用 IntStream,DoubleStreamLongStream

    喜欢这个

    double[] doubleArray = {1.1,1.2,1.3};
    
    DoubleStream.of(doubleArray).forEach(System.out::println);
    
    
    int[] intArray = {1,2,3,4,5,6};
    
    IntStream.of(intArray).forEach(System.out::println);
    
    
    long[] longArray = {1L,2L,3L};
    
    LongStream.of(longArray).forEach(System.out::println);
    

    【讨论】:

    • 我的回答有什么问题?至少你应该发表评论。
    • 确实有帮助,如何将 int[] 分数转换为流。
    • 现在好多了 +1
    【解决方案2】:

    第二个代码sn-p不起作用的原因是Java中没有List<int>这样的东西。这就是为什么Arrays.asList(scores) 不会产生您期望的结果。

    int[] 切换到Integer[] 可以解决这个问题,因为两段代码会产生相同的结果。但是,您的代码效率会降低,因为所有ints 都会被装箱。

    事实上,效率是原始数组重载stream 的原因。你的电话Arrays.stream(scores) 被路由到stream(int[] array),产生IntStream 对象。现在您可以申请.forEach(System.out::println),它调用println(int),再次避免拳击。

    【讨论】:

    • 为瓦尔哈拉计划祈祷然后:D
    • @java8.being:因为为int[] 编写包装器List 大约需要十行代码,而对于流式传输,Arrays.stream(scores) 已经可以工作,我看不出有什么意义为我们甚至不知道这个问题会发生什么以及如何改变的事情祈祷……
    • @Holger 我指的是这条线:The reason the second code snippet does not work is that there is no such thing as List<int> in Java.
    • @java8.being:如果 Valhalla 项目设法改变这一点,List<int>List<@NonNull Integer> 之间将没有真正的区别,Arrays.asList 将继续做它今天所做的事情,出于兼容性原因……
    【解决方案3】:

    您看到的行为并非特定于 Streams。 当您将int[] 传递给Arrays.asList(scores) 时,Arrays.asList(scores) 返回一个List<int[]>,因为泛型类型参数不能被基本类型替换。因此,当您调用asList(T... a) 时,编译器使用int[] 代替T

    如果您将scores 更改为Integer[],您将获得预期的输出(即Arrays.asList(scores) 将返回List<Integer>)。

    【讨论】:

    • 我明白了。这很奇怪,因为我记得我过去做过类似的事情,而且效果很好。如果我像这样提前声明列表,它会起作用吗:List<Integer> scoresAsList = new ArrayList<>(scores);
    • @AdHominem 这行不通,因为您不能将数组传递给 ArrayList 构造函数。你只能传递一个集合。
    • 附带说明,Stream.of(scores).forEach(System.out::println);Arrays.asList(scores).stream().forEach(System.out::println); 的作用相同...
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多