I have the following example data set that I want to transform / reduce using Java stream api based on direction\'s value
Direction int[]
IN 1, 2
O
I've got two ideas on this topic. First one is getting the indices like in this answer and group it accordingly.
The second idea - if you already got a Stream
a custom Collector
should be used (similar to the other solutions, though using Deque
):
private Collector> squashTuples() {
return new Collector, List>() {
@Override
public Supplier> supplier() {
return ArrayDeque::new;
}
@Override
public BiConsumer, Tuple> accumulator() {
return (acc, e) -> {
Objects.requireNonNull(e);
if (!acc.isEmpty() && acc.peekLast().getDirection() == e.getDirection()) {
acc.offerLast(acc.pollLast().merge(e));
} else {
acc.offerLast(e);
}
};
}
@Override
public BinaryOperator> combiner() {
return (left, right) -> {
if (!left.isEmpty() && !right.isEmpty() && left.peekLast().getDirection() == right.peekFirst().getDirection()) {
left.offerLast(left.pollLast().merge(right.pollFirst()));
}
left.addAll(right);
return left;
};
}
@Override
public Function, List> finisher() {
return ArrayList::new;
}
@Override
public Set characteristics() {
return EnumSet.noneOf(Characteristics.class);
}
};
}