Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 362
Hind Forsum Avatar asked Nov 16 '18 07:11

Hind Forsum


2 Answers

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());
like image 159
Eran Avatar answered Nov 14 '22 22:11

Eran


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.

like image 38
Slaw Avatar answered Nov 14 '22 23:11

Slaw