我能否使用Java 8的stream()将一个非基本类型项目的数组转换为List?

huangapple go评论56阅读模式
英文:

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 &#39;use stream()&#39; - um, why? Stream is a tool. For this job, that&#39;s a bit like asking: &quot;Hey, can I hammer in a nail.... using a shoe?&quot;. I guess, maybe? Shoes are great if you&#39;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>



huangapple
  • 本文由 发表于 2020年8月19日 08:48:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63478521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定