Search code examples
javaconcatenationstring-concatenation

Interleave two string arrays


In Java, I have something like this:

String[] firstname = { "name1", "name2", "name3" }; 
String[] lastname = { "lastname1", "lastname2", "lastname3" };

and the result I need would be something like this:

String[] newArray = {"name1 lastname1", "name2 lastname2", "name3 lastname3"};

combining one by one name lastname into String[] newArray assuming the lengths are the same.


Solution

  • The Java 7 and earlier way might be to just use a loop and iterate over all first and last names:

    String[] fullname = new String[firstname.length];
    for (int i=0; i < firstname.length; ++i) {
        fullname[i] = firstname[i] + " " + lastname[i];
    }