-1

I've been looking up for a while how to "collect" an IntStream into a List thus generating a random int list, but the compiler keeps complaining. Piece of code below:

IntStream randIntStream = new Random().ints(1000);
List<Integer> randomInts =
randIntStream.collect(Collectors.toCollection(ArrayList::new));

Error given by compiler:

Error:(42, 49) java: method collect in interface java.util.stream.IntStream cannot be applied to given types;

required: java.util.function.Supplier,java.util.function.ObjIntConsumer,java.util.function.BiConsumer

found: java.util.stream.Collector> reason: cannot infer type-variable(s) R (actual and formal argument lists differ in length)

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
Cris
  • 549
  • 5
  • 21

1 Answers1

4

Before you can collect an IntStream to a List<Integer>, you need to call IntStream#boxed to transform it into a Stream<Integer>:

IntStream randIntStream = new Random().ints(1000);
List<Integer> randomInts = randIntStream.boxed()
    .collect(Collectors.toCollection(ArrayList::new));
Jacob G.
  • 28,856
  • 5
  • 62
  • 116