Ale*_* P. 3 lambda java-8 java-stream
我有一个这个描述的练习:
1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
Run Code Online (Sandbox Code Playgroud)
我写了以下代码:
String inputString = "1111"; // taking this number as example
int sum = 0;
for (int i = 0; i < inputString.length() - 1; i++) {
if (inputString.charAt(i) == inputString.charAt(i + 1)) {
sum += Integer.parseInt(String.valueOf(inputString.charAt(i)));
}
if (i + 2 == inputString.length() - 1) {
if (inputString.charAt(i + 2) == inputString.charAt(0)) {
sum += Integer.parseInt(String.valueOf(inputString.charAt(i + 2)));
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果sum是4,这是正确的.
现在我正在尝试使用lambda在Java8中编写相同的一个,但我无法弄清楚如何获取流中的最后一个条件.
这是我得到了多远:
Integer sum = IntStream.range(0, (inputString.length() - 1)).boxed()
.filter(j -> inputString.charAt(j) == inputString.charAt(j + 1))
.mapToInt(i -> Integer.parseInt(String.valueOf(inputString.charAt(i)))).sum();
Run Code Online (Sandbox Code Playgroud)
如果你考虑循环变量的模数,最后一个条件实际上和其他条件一样: ((length-1) + 1) % length == 0
int length = inputString.length();
IntStream.range(0, length)
.filter(i -> inputString.charAt(i) == inputString.charAt((i + 1) % length))
.map(i -> Integer.parseInt(String.valueOf(inputString.charAt(i))))
.sum();
Run Code Online (Sandbox Code Playgroud)