【问题标题】:How to convert IntStream to List in java? [duplicate]如何在java中将IntStream转换为List? [复制]
【发布时间】:2021-08-10 11:08:12
【问题描述】:

我想将随机数流转换为列表:

public static void main(String[] args) {
        System.out.println(
                new Random().ints(10, 0, 20).
                        collect(Collectors.toList()));
    }

但这给出了一个例外

java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
  required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
  found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.List<java.lang.Object>>
  reason: cannot infer type-variable(s) R
    (actual and formal argument lists differ in length)

那么如何在 java 中将流转换为列表?

【问题讨论】:

标签: java list java-stream


【解决方案1】:

说明

Random#ints 返回IntStream,而不是Stream&lt;Integer&gt;,这就是问题所在。

IntStream 是一个特殊的类来表示原始ints。但是Java中的泛型不支持原语,即没有List&lt;int&gt;。所以你首先必须让你的ints Integers,包装类。然后就可以收藏到List&lt;Integer&gt;


解决方案

只需装箱它就可以了。

stream.boxed().toList() // since Java 16
// or
stream.boxed().collect(Collectors.toList())

另见IntStream#boxed的文档:

返回一个由该流的元素组成的流,每个元素都装箱成一个整数。

为了理解,boxed() 大致相当于

stream.mapToObj(x -> Integer.valueOf(x))

所以在你的情况下:

public static void main(String[] args) {
    System.out.println(
        new Random()
            .ints(10, 0, 20)
            .boxed()
            .toList());
}

【讨论】:

    【解决方案2】:

    List 不能包含原语,因此您需要使用包装类型,例如 Integer。为此,请在调用 collect() 之前调用 boxed()(它将您的 IntStream 转换为 Stream&lt;Integer&gt;)。

    public static void main(String[] args) {
            System.out.println(
                    new Random().ints(10, 0, 20).boxed().
                            collect(Collectors.toList()));
    }
    

    【讨论】:

    • (注意 Stream#toList() 是一个东西,因为 Java 16)
    • 很高兴知道,虽然我的答案通常基于 Java 的 LTS 版本,即 11
    【解决方案3】:

    您需要调用boxed 才能从IntStream 获取Stream&lt;Integer&gt; 并访问所需的collect 重载方法:

    new Random().ints(10, 0, 20)
                .boxed()
                .collect(Collectors.toList());
    

    【讨论】:

    • (注意 Stream#toList() 是一个东西,因为 Java 16)
    【解决方案4】:

    只需在您的 IntStream 引用中使用 .boxed()。

    例如:

    import java.util.List;
    import java.util.Random;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    public class Java8 {
        public static void main(String[] args) {
            IntStream ints = new Random().ints(10, 0, 20); //here ints is your intstream
            List<Integer> collect = ints.boxed().collect(Collectors.toList()); 
    /*
      Here Just use ints.boxed() and then collect to list 
    */
            collect.forEach(System.out::println);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 2019-12-03
      • 2014-07-03
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多