I need help on solving this problem,I have two Strings
String s1 = "Mohan";
String s2 = "1234567";
I need output as
"M1o2h3a4n567"
like s1 first character then s2 first character.
How can I solve this using java8 stream API?
I converted two strings to a list then in stream API tried to use reduce but I know this is not the right solution.
Well, there are a whole lot of options, each one with advantages and disadvantages.
Here's another way, using an IntStream and a StringBuilder:
String result = IntStream.range(0, Math.max(s1.length(), s2.length()))
.collect(
StringBuilder::new,
(sb, i) -> {
if (i < s1.length()) {
sb.append(s1.charAt(i));
}
if (i < s2.length()) {
sb.append(s2.charAt(i));
}
},
StringBuilder::append
)
.toString();
What happens here is that we loop (using an IntStream) over all indexes of the largest of both strings (using max(s1.length(), s2.length())).
Then we collect into a StringBuilder, adding the character from s1 if it exists, and then the same for s2.
Note that this code doesn't use any intermediate substrings.
However, I think an ol' skool for or foreach loop is just as good as using streams.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With