java IntStream cannot use collect(Collectors.toList()), compilation error, why? [duplicate]
Asked Answered
B

2

6

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?

Brewington answered 16/11, 2018 at 7:44 Comment(1)
Call boxed () before collecting.Beneficent
T
5

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.

Tambourine answered 16/11, 2018 at 7:51 Comment(0)
C
7

The primitive streams don't have the same collect method as Stream. You can convert them to a stream of the wrapper type in order to use the collect method that accepts a Collector argument:

List<Integer> list1 = iStream.boxed().collect(Collectors.toList());
Callus answered 16/11, 2018 at 7:46 Comment(0)
T
5

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.

Tambourine answered 16/11, 2018 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.