如何在 Stream.Concat 后流式传输内容,以避免中间列表。

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

How to stream the contents after Stream.Concat to avoid intermediate List

问题

我有两个列表 A 和 B。我想合并它们,然后再次流式处理以形成一个数组。

我目前的做法是:

List<String> aggregate = Stream.concat(A.stream(), B.stream()).collect(Collectors.toList());
String[] finalArray = aggregate.stream().limit(10).collect(Collectors.toList()).toArray(new String[10]);

在这里,我有两个中间列表,我只是用它们来获取最终的数组。是否有一种方法可以在一行内消除这两个 collect(Collectors.toList()) 并将其写成单行?

谢谢

英文:

I have two Lists A and B. I would like to merge them and stream again to form an Array.

I'm currently doing:

List&lt;String&gt; aggregate  = Stream.concat(A.stream(), B.stream()).collect(Collectors.toList());
String[] final = aggregate.stream().limit(10).collect(Collectors.toList()).toArray(new String[10]);

Here, I'm having two intermediate lists that I'm just using to grab the final Array. Is there a way I can eliminate the two collect(Collectors.toList()) and write this in a single line?

Thank you

答案1

得分: 3

你不需要收集,可以直接使用 .toArray()

String[] res = Stream.concat(A.stream(), B.stream()).limit(10).toArray(String[]::new);

如果你想要连接流并且分开地将其作为数组获取,而不进行收集:

Stream<String> aggregate = Stream.concat(A.stream(), B.stream());
String[] res = aggregate.limit(10).toArray(String[]::new);
英文:

You don't need to collect at all you can directly use .toArray()

String[] res = Stream.concat(A.stream(), B.stream()).limit(10).toArray(String[]::new);

And if you want concat the stream and then get as array separately without collecting

Stream&lt;String&gt; aggregate  = Stream.concat(A.stream(), B.stream());
String[] res = aggregate.limit(10).toArray(String[]::new);

答案2

得分: 1

使用这种方式

Stream.concat(A.stream(), B.stream()).collect(Collectors.toList());

这将返回一个列表。如果你想要将其变成一个数组,可以使用以下代码

Stream.concat(A.stream(), B.stream()).toArray(String[]::new);

对于多个流,我们可以像这样处理

Stream.concat(firstStream, Stream.concat(secondStream, Stream.concat(thirdStream, fourthStream))).toArray(String[]::new);

希望对你有所帮助。

英文:

Use this way

Stream.concat(A.stream(), B.stream()).collect(Collectors.toList());

This will return a list. If you want to be it an array, then do

 Stream.concat(A.stream(), B.stream()).toArray(String[]::new);

for multiple streams we can do like

Stream.concat(firstStream, concat(secondStream, concat(thirdStream, fourthStream))).toArray(String[]::new);

I hope it helps

huangapple
  • 本文由 发表于 2020年7月27日 22:23:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63117385.html
匿名

发表评论

匿名网友

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

确定