有一个方法,生成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/