0

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.

2
  • Are you using Java? Commented Mar 13, 2017 at 23:55
  • sorry, yes.... I've edited already. Thanks for your answer below. Commented Mar 14, 2017 at 0:23

2 Answers 2

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Java 8's Stream API and index both arrays with an stream of integers.

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

        String[] newArray = IntStream.range(0, firstname.length).boxed()
                .map(i -> firstname[i] + " " + lastname[i]).toArray(String[]::new);

        System.out.println(Arrays.toString(newArray));

This yields

[name1 lastname1, name2 lastname2, name3 lastname3]

This answers assumes, that the length of lastname is at least the length of firstname, but OP already stated that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.