Java: making List from primitive array using Stream API

守給你的承諾、 提交于 2019-12-30 10:51:53

问题


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?


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/27572859/java-making-list-from-primitive-array-using-stream-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!