How to apply operation every nth element
Solution 1:
I believe this is what you are looking for:
public static void main(String[] args) {
String string = "12345";
String result = IntStream.range(0, string.length())
.mapToObj(index -> incrementCharAtEvenIndex(string, index, 3))
.collect(Collectors.joining());
System.out.println(result);
}
static String incrementCharAtEvenIndex(String string, int index, int increment) {
int number = Character.getNumericValue(string.charAt(index));
if ((index + 1) % 2 == 0) {
number = number + increment;
}
return String.valueOf(number);
}
Unfortunately, Stream API is not built to work with the indices directly, so you have to use IntStream to simulate for-loop and a custom method to increment a numeric character if it appears at the even index (remember it starts at 0).
Solution 2:
You can use the range operator to add a index to your stream:
String myString = "12345";
int n = 2;
IntStream
.range(0, myString.length())
.mapToObj(i -> Map.entry(i, Character.getNumericValue(myString.charAt(i))))
.mapToInt(pair -> (pair.getKey() + 1) % n == 0 ? pair.getValue() + 3 : pair.getValue())
.forEach(System.out::print);