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
This is an alternative approach that uses slightly different data structures.
If this is an option, changing from int[]
to List
allows for more flexibility (not to mention avoiding creating/copying arrays multiple times):
class Tuple {
Direction direction;
List data;
}
And the following function does the merging on a Deque
collection:
private static List next(Deque t, Direction d) {
if (!t.isEmpty() && t.peekLast().getDirection() == d) {
return t.peekLast().getData();
} else {
Tuple next = new Tuple();
next.direction = d;
next.data = new ArrayList<>();
t.addLast(next);
return next.data;
}
}
And with that, the stream can look as simple as:
Deque deq = new LinkedList<>(); //the final collection of tuples
tuples.stream()
.flatMap(tp -> tp.getData().stream()
.map(d -> Pair.of(tp.getDirection(), Integer.valueOf(d))))
.forEach(el -> next(deq, el.getLeft()).add(el.getRight()));