java - 使用流 API 将 arraylist 添加到 arraylist

标签 java collections stream

有一个方法,生成ArrayList:

List<Entity> method (String s){
    ........
    return list;
} 

如何使用流API从列表集合中收集列表? (类似于 newList.addAll(list);

List<String> stringList = someGenerateStrings();

List<Entity> newList = stringList.stream()
    .map(this::method)
    .collect(?)

最佳答案

首先,您需要将列表流展平为列表元素流。您可以使用Stream's flatMap method :

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

这基本上将元素从您创建的内部 Stream 中取出并放入主 Stream 中。

.flatMap(p -> method(p).stream())

然后就像收集到列表一样简单。

.collect(Collectors.toList());

关于java - 使用流 API 将 arraylist 添加到 arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52193797/

相关文章:

python - 如何在 python 3.4 中预处理 yaml 文件?

android - VLC RTSP 直播到 Android

c# - 用于 Android 或 Java 和 WCF 的单声道

java - CountNonDivisible - Codility 训练任务

java - 如何将嵌套数组列表转换为数组列表?

collections - Kotlin 将带有可空值的列表转换为不带可空值的 HashMap

swift utf16 数据流 - 分成 block 的问题

java - Spring Cloud Dataflow 文件启动器修改

java - java中可以比较两个不同的对象吗?

Java:如何将 String[] 转换为 List 或 Set