4

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?

0

4 Answers 4

11

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());
Sign up to request clarification or add additional context in comments.

1 Comment

+ 1 for finding the real problem and the real solution
2

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));

Comments

2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.