Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat two Strings by each character by using java8 stream API? [duplicate]

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.

like image 913
Bijaya Bhaskar Swain Avatar asked Dec 21 '25 14:12

Bijaya Bhaskar Swain


1 Answers

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.

like image 150
MC Emperor Avatar answered Dec 23 '25 03:12

MC Emperor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!