chnging
chnging

Reputation: 775

Java: making List from primitive array using Stream API

I'm trying to make 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 collect gives me an error because it wants other arguments. It wants 3 arguments Supplier, ObjIntConsumer and BiConsumer.

I don't understand why it wants 3 arguments when I have seen different examples that just use collect(Collectors.toList()); and get the list.

What I'm doing wrong?

Upvotes: 4

Views: 1781

Answers (4)

Donald Raab
Donald Raab

Reputation: 6706

If you're open to using a 3rd party library and would like to avoid boxing the int values as Integer objects, you could use primitive lists in Eclipse Collections.

int[] values = {4, 5, 2, 3, 42, 60, 20};
IntList list = IntLists.mutable.withAll(
        Arrays.stream(values).filter(value -> value > 4));

Assertions.assertEquals(IntLists.mutable.with(5, 42, 60, 20), list);

You can also convert the IntStream to an IntArrayList using the collect method, but it is more verbose.

IntList list = Arrays.stream(values).filter(value -> value > 4)
        .collect(IntArrayList::new, IntArrayList::add, IntArrayList::addAll);

Assertions.assertEquals(IntLists.mutable.with(5, 42, 60, 20), list);

You can also just construct the primitive list directly from the primitive array, and use the select method which is an inclusive filter.

IntList list = IntLists.mutable.with(values).select(value -> value > 4);

Assertions.assertEquals(IntLists.mutable.with(5, 42, 60, 20), list);

I have blogged about primitive collections in Eclipse Collections here.

Note: I am a committer for Eclipse Collections.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201537

You're using an array of primitives for one thing, not Integer. I suggest you use Arrays.asList(T...) like

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

Upvotes: 2

sol4me
sol4me

Reputation: 15718

You can change int[] values={4,5,2,3,42,60,20}; to Integer[] values={4,5,2,3,42,60,20}; because currently you are passing an array of primitive type(int) but should you pass array of object i.e. Integer

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93902

Yes this is because Arrays.stream returns an IntStream. You can call boxed() to get a Stream<Integer> and then perform the collect operation.

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

Upvotes: 11

Related Questions