Search code examples
javacompilationjava-streamcollecttolist

java IntStream cannot use collect(Collectors.toList()), compilation error, why?


As below:

    IntStream iStream = IntStream.range(1,4);
    iStream.forEach(System.out::print);
    List list1 = iStream.collect(Collectors.toList());//error!

Java 1.8 compiler gives type deduction error. Similar code could work for String type:

    List<String> ls = new ArrayList<>();
    ls.add("abc");
    ls.add("xyz");
    List list2 = ls.stream().collect(Collectors.toList());

Why? Does IntStream/LongStream/DoubleStream are not working the same way like other types? How to fix my compilation error?


Solution

  • IntStream (along with the other primitive streams) does not have a collect(Collector) method. Its collect method is: collect(Supplier,ObjIntConsumer,BiConsumer).

    If you want to collect the ints into a List you can do:

    List<Integer> list = IntStream.range(0, 10).collect(ArrayList::new, List::add, List::addAll);
    

    Or you can call boxed() to convert the IntStream to a Stream<Integer>:

    List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());
    

    Both options will box the primitive ints into Integers, so which you want to use is up to you. Personally, I find the second option simpler and clearer.