|
| 1 | +package com.fasterxml.jackson.databind.util; |
| 2 | + |
| 3 | +import java.util.stream.Collector; |
| 4 | + |
| 5 | +import com.fasterxml.jackson.databind.JsonNode; |
| 6 | +import com.fasterxml.jackson.databind.node.ArrayNode; |
| 7 | +import com.fasterxml.jackson.databind.node.JsonNodeCreator; |
| 8 | +import com.fasterxml.jackson.databind.node.JsonNodeFactory; |
| 9 | + |
| 10 | +/** |
| 11 | + * Utility class that provides custom {@link Collector} implementations to support Stream operations. |
| 12 | + * <p> |
| 13 | + * This class is not meant to be instantiated and serves only as a utility class. |
| 14 | + * </p> |
| 15 | + * |
| 16 | + * @since 2.18 |
| 17 | + */ |
| 18 | +public abstract class JacksonCollectors { |
| 19 | + /** |
| 20 | + * Creates a {@link Collector} that collects {@link JsonNode} elements into an {@link ArrayNode}. |
| 21 | + * <p> |
| 22 | + * This method uses a {@link JsonNodeFactory} to create an empty {@link ArrayNode} and then adds each |
| 23 | + * {@link JsonNode} to it. |
| 24 | + * </p> |
| 25 | + *<p> |
| 26 | + * Short-cut to |
| 27 | + *{@code toArrayNode(JsonNodeFactory.instance}} |
| 28 | + * |
| 29 | + * @return a {@link Collector} that collects {@link JsonNode} elements into an {@link ArrayNode} |
| 30 | + */ |
| 31 | + public static Collector<JsonNode, ArrayNode, ArrayNode> toArrayNode() { |
| 32 | + return toArrayNode(JsonNodeFactory.instance); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Creates a {@link Collector} that collects {@link JsonNode} elements into an {@link ArrayNode}. |
| 37 | + * <p> |
| 38 | + * This method uses a {@link JsonNodeFactory} to create an empty {@link ArrayNode} and then adds each |
| 39 | + * {@link JsonNode} to it. |
| 40 | + * </p> |
| 41 | + * |
| 42 | + * @param nodeCreator Factory for constructing {@link ArrayNode} to contain nodes in |
| 43 | + * |
| 44 | + * @return a {@link Collector} that collects {@link JsonNode} elements into an {@link ArrayNode} |
| 45 | + */ |
| 46 | + public static Collector<JsonNode, ArrayNode, ArrayNode> toArrayNode(JsonNodeCreator nodeCreator) { |
| 47 | + return Collector.of( |
| 48 | + nodeCreator::arrayNode, // supplier |
| 49 | + ArrayNode::add, // accumulator |
| 50 | + ArrayNode::addAll // combiner |
| 51 | + ); |
| 52 | + } |
| 53 | +} |
0 commit comments