英文:
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<String> 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<String> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论