我有List<Vector3D>
,其中Vector3D
是一个坐标。我想找到列表中Vector3D
个元素之间所有距离的总和。我想用java 8流找到它。我尝试使用reduce
,但它无法帮助我。
UPD:
类Vector3D
让方法double distance(Vector3D)
找到两个位置之间的距离。例如我有(1,0,0)(2,0,0)(3,0,0)的列表。结果我想找到这条路的长度。这是3。
如果我们使用java 7或更低版本,我们必须这样做:
public static double calcPathLength(List<Vector3D> path){
double length = 0d;
for (int i=0; i< path.size()-1; i++){
length += path.get(i).distance(path.get(i+1));
}
return length;
}
答案 0 :(得分:3)
您正在执行的操作称为Mutable reduction。
Pshemo’s answer显示了如何通过提供三个必要的功能来临时实现此类操作。但是,当所有三个函数都由专用类实现时,在实现Collector
的类中实现这些函数以便于重用可能是有用的:
public class Distance implements Collector<Vector3D, Distance.Helper, Double> {
public static final Distance COLLECTOR = new Distance();
static final class Helper {
private double sum = 0;
private Vector3D first = null, previous = null;
}
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
public Supplier<Helper> supplier() {
return Helper::new;
}
public BiConsumer<Helper, Vector3D> accumulator() {
return (helper,vector3d)-> {
if (helper.previous != null)
helper.sum += vector3d.distance(helper.previous);
else helper.first = vector3d;
helper.previous = vector3d;
};
}
public BinaryOperator<Helper> combiner() {
return (h1,h2)-> {
h2.sum += h1.sum;
if(h1.previous!=null && h2.first!=null) {
h2.sum += h1.previous.distance(h2.first);
h2.first=h1.first;
}
return h2;
};
}
public Function<Helper, Double> finisher() {
return helper -> helper.sum;
}
}
您将从ad-hoc版本中识别出三个功能。 New是第四个函数finisher
,它允许指定如何从可变容器中提取最终结果,因此我们不需要getSum()
调用。
用例简化为:
List<Vector3D> list;
//…
double distance=list.stream().collect(Distance.COLLECTOR);
答案 1 :(得分:2)
其中一个选项是创建一些辅助类,它会记住以前使用过的向量,并根据它计算它与当前向量之间的差异。这个类看起来像
class DistanceHelper {
private double sum = 0;
private Vector3D first = null;
private Vector3D last = null;
public void add(Vector3D vector3d) {
if (first == null)
first = vector3d;
if (last != null)
sum += vector3d.distance(last);
last = vector3d;
}
public void combine(DistanceHelper otherHelper) {
//add distance of path from current thread with distance of path
//from other thread
sum += otherHelper.sum;
//also add distance between paths handled by separate threads like
// when path of Thread1 is A->B and Thread2 is C->D then we need to
// include path from `B` to `C`
if (this.last!=null && otherHelper.first!=null)
sum += this.last.distance(otherHelper.first);
this.last = otherHelper.last;
}
public double getSum() {
return sum;
}
}
您可以将其用作combine
代替reduce
的
double sum = list
.stream()//or parallelStream()
.collect(DistanceHelper::new, DistanceHelper::add,
DistanceHelper::combine).getSum();