Java:使用Stream API从原始数组制作List [英] Java: making List from primitive array using Stream API

查看:176
本文介绍了Java:使用Stream API从原始数组制作List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从原始数组中创建一个List

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

但最后一个函数 collect 给了我一个错误,因为它想要其他参数。它需要3个参数Supplier,ObjIntConsumer和BiConsumer。

But the last function collect gives me an error because it wants other arguments. It wants 3 arguments Supplier, ObjIntConsumer and BiConsumer.

当我看到只使用的不同示例时,我不明白为什么它需要3个参数收集(Collectors.toList()); 并获取清单。

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.

我做错了什么?

推荐答案

是的,这是因为 Arrays.stream 返回 IntStream 。您可以调用 boxed()来获取 Stream< Integer> ,然后执行收集操作。

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

这篇关于Java:使用Stream API从原始数组制作List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆