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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Hind Forsum
  • 9,717
  • 13
  • 63
  • 119

2 Answers2

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());
Eran
  • 387,369
  • 54
  • 702
  • 768
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.

Slaw
  • 37,820
  • 8
  • 53
  • 80