我有一个这样描述的练习:
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.
我写了以下代码:
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)));
}
}
}
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();
最佳答案
如果您考虑循环变量以长度为模,最后一个条件实际上与其他条件一样:((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();
关于lambda - 使用 lambda 在 java8 中具有双重条件的 Foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47643187/