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 think your solution is pretty nice already, especially as using a reduction enables parallelism easily compared to collecting into a shared outside container. But it's easier to use collect
instead of reduce
as Holger pointed out. Furthermore, the conditions in the accumulator can be simplified a bit, and you forgot to merge the last and first elements in the combiner:
List reduce = tupleStream.collect(ArrayList::new, WDParser::add, WDParser::combine);
private static List combine(List list1, List list2)
{
if (!list2.isEmpty())
{
add(list1, list2.remove(0)); // merge lists in the middle if necessary
list1.addAll(list2); // add all the rest
}
return list1;
}
private static List add(List list, Tuple t)
{
int lastIndex = list.size() - 1;
if (list.isEmpty() || list.get(lastIndex).getDirection() != t.getDirection())
{
list.add(t);
}
else
{
list.set(lastIndex, list.get(lastIndex).merge(t));
}
return list;
}
Instead of using indexes to access the first/last element you could even use LinkedList
and the methods add/removeFirst/Last()
.