英文:
Can i convert an array of non-primitive items to a List using Java 8's stream()?
问题
大多数我在这里看到的示例都解释了如何将基本数据类型的数组转换为ArrayList。
是否可以使用stream()将非基本数据类型的数组转换为ArrayList?
如果不行,是否有工具可以实现相同的功能?
英文:
Most examples i see here explain how to convert an array of primitives to ArrayList.
Is it possible to use stream() to convert an array of non-primitives into an ArrayList?
If not, is there a utility to do the same ?
答案1
得分: 2
当然,简单的答案是:
```java
String[] array = ...;
List<String> list = List.of(array);
你提到要使用 stream()
- 嗯,为什么呢?Stream 是一个工具。对于这个任务来说,这有点像在问:“嘿,我能用一只鞋子来钉钉子吗?”。我猜,也许可以?如果你要去跑步,鞋子是很棒的,但在试图固定钉子时并不合适。使用锤子。
但是如果你想的话,当然可以使用 Arrays.stream(array).collect(Collectors.toList());
,但这样写更多,更慢,不够惯用,基本上在所有方面都更糟糕。
<details>
<summary>英文:</summary>
The trivial answer is of course:
String[] array = ...;
List<String> list = List.of(array);
You mention 'use stream()' - um, why? Stream is a tool. For this job, that's a bit like asking: "Hey, can I hammer in a nail.... using a shoe?". I guess, maybe? Shoes are great if you're going for a run, not appropriate when trying to fasten a nail. Use a hammer.
But if you want to.. sure.. `Arrays.stream(array).collect(Collectors.toList());`, but this is more typing, slower, less idiomatic, and basically in all ways worse.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论