java - How do I rewrite this double for loop with a an if else using Java 8 lambdas?
问题描述
I am trying to rewrite this piece of code using Java 8 lambdas. But so far, I couldn't think of any way to handle if and else together.
for (int i = 0; i<= m; i++)
{
for (int j = 0; j <=n ; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
解决方案
将您的代码转换为 lambda:
Runnable lambda = () -> {
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
};
lambda.run();
哦,你的意思是带有 lambda 的流?
IntStream.rangeClosed(0, m).forEachOrdered(i -> {
IntStream.rangeClosed(0, n).forEachOrdered(j -> {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
});
});
哦,你不想要 lambda{}
块?
IntStream.rangeClosed(0, m).forEachOrdered(i ->
IntStream.rangeClosed(0, n).forEachOrdered(j ->
L[i][j] = (i == 0 || j == 0 ? 0
: X.charAt(i-1) == Y.charAt(j-1) ? L[i-1][j-1] + 1
: Math.max(L[i-1][j], L[i][j-1]))
)
);
并不是说我看到了做任何事情的意义。
推荐阅读
- javascript - Angular 7 - [object Object] 接收作为输出
- indexing - 索引来自多个数据源(CSV、RDBMS)的数据
- html5-video - 加载后如何暂停Shaka播放器?
- view - SwiftUI:从先前视图未覆盖的滑块菜单中启动新视图
- angular - 如何将参数传递给Angular中的路由
- awk - awk/grep/sed:在我的文件的一行中找到多个模式
- django - 我如何访问 wordpress 数据/仪表板?
- java - 具有偶数或奇数的 ArrayList
- c++ - 针对特定版本的应用程序
- r - 如何使用R中一列中的数据制作多个图?