我/如何更改以下方法以使用流?
在命令式编程风格中,我存储了先前的city值,并且不得不使用它来获取下一个值,请参见e.getOther()
(不要问我为什么)。
问题的重点是:如何使用streams / lambda实现相同的输出?
private <V extends City, E extends WeightedEdge<V>> void printWeightedEdgePath(List<E> pathList, V srcVertex, V destVertex) {
PrintVisitor printVisitor = new PrintVisitor();
if (!pathList.isEmpty()) {
V atThisCity = srcVertex;
System.out.printf("%s to %s: %s", srcVertex, destVertex, srcVertex);
pathList.stream().forEach(edge -> { // stream way - error
printVisitor.accept(edge);
System.out.printf(" --%2.2f-->", e.weight());
atThisCity = e.getOther(atThisCity); // variable must be final
printVisitor.accept(atThisCity);
});
System.out.println();
} else {
System.out.printf("%s to %s: not connected\n", srcVertex, destVertex);
}
System.out.println();
}
编辑:感谢@Bohemian技巧-使用obj数组最终欺骗Java。
private <V extends City, E extends Edge<V>> void printEdgePath(List<E> pathList, V srcVertex, V destVertex) {
PrintVisitor printVisitor = new PrintVisitor();
if (!pathList.isEmpty()) {
Vertex [] atThisCity = new Vertex[]{srcVertex};
System.out.printf("%s to %s: %s", srcVertex, destVertex, srcVertex);
pathList.stream().forEach(edge -> {
printVisitor.accept(edge);
@SuppressWarnings("unchecked")
V nextCity = edge.getOther((V)atThisCity[0]);
atThisCity[0] = nextCity;
printVisitor.accept(atThisCity[0]);
});
System.out.println();
} else {
System.out.printf("%s to %s: not connected\n", srcVertex, destVertex);
}
System.out.println();
}
最佳答案
以下是为避免“有效最终”要求而进行的工作:
如果需要修改lambda中的值,请使用数组。当数组是最终数组时,其内容可能会发生突变。即:
Object[] array = new Object[1];
someStream.forEach(o -> {processPreviousAndCurrent(array[0], o); array[0] = o;});
在这个简单的示例中,数组保留先前的值。
在您的示例中,执行以下操作:
private <V extends City, E extends WeightedEdge<V>> void printWeightedEdgePath(List<E> pathList, V srcVertex, V destVertex) {
PrintVisitor printVisitor = new PrintVisitor();
if (!pathList.isEmpty()) {
Object[] atThisCity = new Object[]{srcVertex};
System.out.printf("%s to %s: %s", srcVertex, destVertex, srcVertex);
pathList.stream().forEach(edge -> {
printVisitor.accept(edge);
System.out.printf(" --%2.2f-->", e.weight());
atThisCity[0] = e.getOther((V)atThisCity[0]);
printVisitor.accept(atThisCity);
});
System.out.println();
} else {
System.out.printf("%s to %s: not connected\n", srcVertex, destVertex);
}
System.out.println();
}