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]);
}
}
Turning your code into a 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();
Oh, you meant streams with lambdas?
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]);
});
});
Oh, you don't want lambda {}
blocks ?
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]))
)
);
Not that I see the point of doing any of it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.