Java 中将数组存入集合的方法有:使用 Collection.addAll、利用 Arrays.stream、借助 Java 8+ API IntStream.of 和采用循环遍历。

Java 中将数组存入集合
方法一:使用 Collection.addAll
<code class="java">List<Integer> list = new ArrayList<>();
int[] arr = {1, 2, 3, 4, 5};
// 将数组元素逐个添加到集合中
list.addAll(Arrays.asList(arr));
// 或者,使用简化写法
list.addAll(arr);</code>方法二:使用 Arrays.stream
<code class="java">List<Integer> list = Arrays.stream(arr).boxed().toList();</code>
方法三:使用 Java 8 及更高版本的 API
立即学习“Java免费学习笔记(深入)”;
<code class="java">List<Integer> list = IntStream.of(arr).boxed().toList();</code>
方法四:使用循环
<code class="java">List<Integer> list = new ArrayList<>();
for (int element : arr) {
list.add(element);
}</code>以上就是java怎么把数组存入集合的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号