13
13
* See the License for the specific language governing permissions and
14
14
* limitations under the License.
15
15
*/
16
-
17
16
package org .springframework .batch .item ;
18
17
18
+ import java .util .function .Function ;
19
+
19
20
import org .springframework .lang .NonNull ;
20
21
21
22
/**
37
38
* @author Lucas Ward
38
39
* @author Taeik Lim
39
40
* @author Mahmoud Ben Hassine
41
+ * @author Stefano Cordio
40
42
*/
41
43
@ FunctionalInterface
42
44
public interface ItemWriter <T > {
@@ -50,4 +52,27 @@ public interface ItemWriter<T> {
50
52
*/
51
53
void write (@ NonNull Chunk <? extends T > chunk ) throws Exception ;
52
54
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
+
53
78
}
0 commit comments