Java: creating a list from a primitive array using Stream API

I am trying to create a list from a primitive array

int[] values={4,5,2,3,42,60,20};
List<Integer> greaterThan4 =
Arrays.stream(values)
        .filter(value -> value > 4)
        .collect(Collectors.toList());

      

But the last function is collect

giving me an error because it wants other arguments. He wants 3 Vendor arguments, ObjIntConsumer and BiConsumer.

I don't understand why he wants 3 arguments when I saw different examples that just use collect(Collectors.toList());

and get a list.

What am I doing wrong?

+3


source to share


3 answers


Yes, this is because it Arrays.stream

returns IntStream

. You can call boxed()

to get Stream<Integer>

and then do a collect operation.



List<Integer> greaterThan4 = Arrays.stream(values)
                                   .filter(value -> value > 4)
                                   .boxed()
                                   .collect(Collectors.toList());

      

+10


source


You can change int[] values={4,5,2,3,42,60,20};

to Integer[] values={4,5,2,3,42,60,20};

because you are currently passing an array of primitive type ( int

), but you must pass an array of the ie objectInteger



+1


source


You are using an array of primitives for one thing, not Integer

. I suggest you use Arrays.asList(T...)

for example

Integer[] values={4,5,2,3,42,60,20};
List<Integer> al = new ArrayList<>(Arrays.asList(values));

      

+1


source







All Articles