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.

mike
  • 4,929
  • 4
  • 40
  • 80

2 Answers2

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];
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
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.

mike
  • 4,929
  • 4
  • 40
  • 80