Skip to content

Commit c99e805

Browse files
committed
Add mapping adapter to ItemWriter
Signed-off-by: Stefano Cordio <[email protected]>
1 parent 639d64f commit c99e805

File tree

1 file changed

+26
-1
lines changed
  • spring-batch-infrastructure/src/main/java/org/springframework/batch/item

1 file changed

+26
-1
lines changed

spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ItemWriter.java

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@
1313
* See the License for the specific language governing permissions and
1414
* limitations under the License.
1515
*/
16-
1716
package org.springframework.batch.item;
1817

18+
import java.util.function.Function;
19+
1920
import org.springframework.lang.NonNull;
2021

2122
/**
@@ -37,6 +38,7 @@
3738
* @author Lucas Ward
3839
* @author Taeik Lim
3940
* @author Mahmoud Ben Hassine
41+
* @author Stefano Cordio
4042
*/
4143
@FunctionalInterface
4244
public interface ItemWriter<T> {
@@ -50,4 +52,27 @@ public interface ItemWriter<T> {
5052
*/
5153
void write(@NonNull Chunk<? extends T> chunk) throws Exception;
5254

55+
/**
56+
* Adapts an {@code ItemWriter} accepting items of type {@link U} to one accepting
57+
* items of type {@link T} by applying a mapping function to each item before writing.
58+
* <p>
59+
* The {@code mapping()} item writers are most useful when used in combination with a
60+
* {@link org.springframework.batch.item.support.CompositeItemWriter}, where the
61+
* mapping function in front of the downstream writer can be a getter of the input
62+
* item or a more complex transformation logic.
63+
* <p>
64+
* This adapter mimics the behavior of
65+
* {@link java.util.stream.Collectors#mapping(Function, java.util.stream.Collector)}.
66+
* @param <T> the type of the input items
67+
* @param <U> type of items accepted by downstream item writer
68+
* @param mapper a function to be applied to the input items
69+
* @param downstream an item writer which will accept mapped items
70+
* @return an item writer which applies the mapping function to the input items and
71+
* provides the mapped results to the downstream item writer
72+
* @since 6.0
73+
*/
74+
static <T, U> ItemWriter<T> mapping(Function<? super T, ? extends U> mapper, ItemWriter<? super U> downstream) {
75+
return chunk -> downstream.write(new Chunk<>(chunk.getItems().stream().map(mapper).toList()));
76+
}
77+
5378
}

0 commit comments

Comments
 (0)