EN
Java 8 - convert Int Stream to list with Collectors - error fix
5 points
Single method call .boxed()
on IntStream API can fix this problem.
Example:
xxxxxxxxxx
1
IntStream.of(1, 2, 3, 4, 5)
2
.boxed() // <-- this line fix the problem
3
.collect(Collectors.toList());
Full working example
Below we have 2 parts of the code. First part is error reproduction. Second part shows the fix, when we want to convert int stream to list with collect method using int stream and calling boxed method.
xxxxxxxxxx
1
// ERROR reproduction:
2
// Error:(18, 17) java: method collect in interface
3
// java.util.stream.IntStream cannot be applied to given types;
4
// ...
5
// IntStream.of(1, 2, 3, 4, 5)
6
// .collect(Collectors.toList());
7
8
9
// FIX:
10
List<Integer> collect = IntStream.of(1, 2, 3, 4, 5)
11
.boxed() // <-- this line fix the problem
12
.collect(Collectors.toList());
13
14
// [1, 2, 3, 4, 5]
15
System.out.println(collect);
Full stack trace from intellij idea:
xxxxxxxxxx
1
Error:(18, 17) java: method collect in interface java.util.stream.IntStream
2
cannot be applied to given types;
3
required: java.util.function.Supplier<R>,
4
java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
5
found: java.util.stream.Collector<java.lang.Object,capture#1
6
of ?,java.util.List<java.lang.Object>>
7
reason: cannot infer type-variable(s) R
8
(actual and formal argument lists differ in length)
Screenshot with this error:

It is very common problem when we want to collect int stream given from Random class and we call .collect(Collectors.toList())
directly on .ints(size, min, max)
givining us error java.util.stream.IntStream cannot be applied to given types
. The solution is the same as above, we need to call .boxed()
method on IntStream API.
Quick fix:
xxxxxxxxxx
1
new Random()
2
.ints(5, 1, 10)
3
.boxed() // <-- this line fix the problem
4
.collect(Collectors.toList());
Code example with error reproduction and simple fix.
xxxxxxxxxx
1
int size = 5;
2
int min = 1;
3
int max = 10;
4
5
// ERROR:
6
// Error:(26, 67) java: method collect in interface
7
// java.util.stream.IntStream cannot be applied to given types;
8
// ...
9
// List<Integer> list = new Random()
10
// .ints(size, min, max)
11
// .collect(Collectors.toList());
12
13
14
// FIX:
15
List<Integer> list = new Random()
16
.ints(size, min, max)
17
.boxed() // <-- this line fix the problem
18
.collect(Collectors.toList());
19
20
// [5, 9, 4, 3, 4]
21
System.out.println(list);