Java 流减少
2022-09-04 22:17:32
我有以下示例数据集,我想根据方向的值使用Java流API进行转换/减少
Direction int[]
IN 1, 2
OUT 3, 4
OUT 5, 6, 7
IN 8
IN 9
IN 10, 11
OUT 12, 13
IN 14
自
Direction int[]
IN 1, 2,
OUT 3, 4, 5, 6, 7
IN 8, 9, 10, 11
OUT 12, 13
IN 14
到目前为止我编写的代码
enum Direction { IN, OUT }
class Tuple {
Direction direction;
int[] data;
public Tuple merge(Tuple t) {
return new Tuple(direction, concat(getData(), t.getData()));
}
}
private static int[] concat(int[] first, int[] second) {
int[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
List<Tuple> reduce = tupleStream.reduce(new ArrayList<>(), WDParser::add, WDParser::combine);
private static List<Tuple> combine(List<Tuple> list1, List<Tuple> list2) {
System.out.println("combine");
list1.addAll(list2);
return list1;
}
private static List<Tuple> add(List<Tuple> list, Tuple t) {
System.out.println("add");
if (list.size() == 0) {
list.add(t);
} else if (list.size() > 0) {
int lastIndex = list.size() - 1;
Tuple last = list.get(lastIndex);
if (last.getDirection() == t.getDirection())
list.set(lastIndex, last.merge(t));
else
list.add(t);
}
return list;
}
我相信有一个更好,更简单的替代方案来实现同样的目标。
我发现的Java流API reduce/combine的在线示例和博客仅使用Integer::sum函数。希望为更复杂的案例场景建立起来。