Xir*_*dus 5 java lambda java-8 java-stream
我有以下代码:
IntStream.range(0, width).forEach(x1 -> {
IntStream.range(0, height).forEach(y1 -> {
IntStream.rangeClosed(x1-1, x1+1).forEach(x2 -> {
IntStream.rangeClosed(y1-1, y1+1).forEach(y2 -> {
if ((x1 != x2 || y1 != y2) && getNode(x2, y2) != null){
getNode(x1, y1).registerObserverAtNeighbor(getNode(x2, y2));
}
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
有没有办法使用较少的嵌套语句编写上述内容?它基本上是"从(0,0)到(宽度,高度)寄存器观察者的每个节点从(x-1,y-1)到(x + 1,y + 1)的节点,但不是在自身".
你所拥有的基本上是 4 个嵌套循环。这是有道理的,因为您正在迭代矩阵的二维,然后,对于每个节点,您迭代由其邻居组成的小矩阵。
像这样的东西。
0000000
0---000
0-X-000
0---000
0000000
Run Code Online (Sandbox Code Playgroud)
我想您可以仅在语法上使用递归函数,尽管实际上没有任何好处。
iterateLambdas(0, width, 0, height, 1);
public static void iterateLambdas(
int start1,
int end1,
int start2,
int end2,
int depth) {
IntStream.range(start1, end1).forEach(x1 -> {
IntStream.range(start2, end2).forEach(y1 -> {
if (depth != 0) {
iterateLambdas(x1 - 1, x1 + 2, y1 - 1, y1 + 2, depth - 1);
} else {
// Current node : (start1 + 1), (start2 + 1)
// Current neighbour : x1, y1);
// Your logic here
}
});
});
}
Run Code Online (Sandbox Code Playgroud)