在一个流调用中处理、映射和收集对象

Process,map and collect object in one stream call

我有一个对象列表,我想先处理每个对象,然后将它们映射到另一个对象 对象,然后将它们收集到列表中。像这样:

list.stream().forEach(doSomething).map(mapFunction).collect()

但是Java Stream 不支持这个,我在想有没有什么优雅的方法可以达到同样的结果。

forEachterminal operation,因此您无法继续使用流

Terminal operations, such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used;

您可以将 doSomething 移动到 map 方法中,这样它将在映射期间执行

一般用reduction operation代替

the forEach() can simply be replaced with a reduction operation that is safer, more efficient, and more amenable to parallelization

您不能在 forEach 之后使用 map,因为 forEach 没有 return Stream

您可以只在 map 中使用您的 forEach 逻辑,因为它无论如何都会迭代您的整个集合:

list.stream().map(o -> {
    // Foreach logic
    System.out.println(o);
            
    // Map
    return o.toString();
});
list.stream().peek(doSomething).map(mapFunction).collect()