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?
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());
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With