Given the above excerpt from a Java code, I need to modify the code such that it could recursively swap pairs of the content of the string variable, \"locationAddress\". Please
A solution using Stream
:
String input = "abcdefghijk";
String swapped = IntStream.range(0, input.length())
.map(i -> i % 2 == 0 ? i == input.length() - 1 ? i : i + 1 : i - 1)
.mapToObj(input::charAt)
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(swapped); // badcfehgjik
The swapping is driven by the index i
. If i
is even and there is a next (i+1
) character then it's used. If i
is odd then the previous (i-1
) character is used.