Skip to content

Instantly share code, notes, and snippets.

@whitfin
Created September 19, 2015 22:46
Show Gist options
  • Save whitfin/469299fc5558af059cd2 to your computer and use it in GitHub Desktop.
Save whitfin/469299fc5558af059cd2 to your computer and use it in GitHub Desktop.
Collecting to a Jackson ArrayNode from a Java 8 Stream.
package com.zackehh.example;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class ArrayNodeCollector implements Collector<JsonNode, ArrayNode, ArrayNode> {
private static final ObjectMapper mapper
= new ObjectMapper();
@Override
public Supplier<ArrayNode> supplier() {
return mapper::createArrayNode;
}
@Override
public BiConsumer<ArrayNode, JsonNode> accumulator() {
return ArrayNode::add;
}
@Override
public BinaryOperator<ArrayNode> combiner() {
return (x, y) -> {
x.addAll(y);
return x;
};
}
@Override
public Function<ArrayNode, ArrayNode> finisher() {
return accumulator -> accumulator;
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.UNORDERED);
}
}
@YacheLee
Copy link

YacheLee commented Nov 6, 2019

It is useful! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment