'merge two array list in java with specific order

I have two List<String>:

[Adam, Louis, Gorge]
[Backer, Kabi, Tamis]

and I want to combine them to produce one List<String>:

 [Adam Backer, Louis Kabi, Gorge Tamis]

My code:

List<String> firstNames = new ArrayList<String>();
List<String> surNames = new ArrayList<String>();
firstNames.addAll(surNames);

My output:

[Adam, Louis, Gorge, Backer, Kabi, Tamis]


Solution 1:[1]

You could do something like this:

final ArrayList<String> merged = new ArrayList<(firstNames.size());
for (int i = 0; i < firstNames.size(); ++i) {
    merged.add(firstNames.get(i) + " " + surNames.get(i);
}

Solution 2:[2]

//Here is the code for this

//First Create a new List that contained the merged result

//then use a for loop to concat them

import java.util.ArrayList;

import java.util.List;

public class FullName {

public static void main(String [] args)
{
    List<String> firstName = new ArrayList<String>();
    firstName.add("Adam");
    firstName.add("Louis");
    firstName.add("Gorge");
    
    List<String> surName = new ArrayList<String>();
    surName.add("Backer");
    surName.add("Kabi");
    surName.add("Tamis");

    //Here just make a new List to store to first and sur name together
    List<String> fullName = new ArrayList<String>();
    
    //use a for loop 
    //Simplest way to merge both List together
    for(int i=0;i<firstName.size();i++)
    {
        fullName.add(firstName.get(i)+" "+surName.get(i));
    }

    //Displaying the results
    for(int i=0;i<fullName.size();i++)
        System.out.println(fullName.get(i));
}

}

Solution 3:[3]

If list2 is mutable, you can do it in one line:

list1.replaceAll(s -> s + " " + list2.remove(0));

Solution 4:[4]

This is a good use case for the StreamEx library's zip method:

import one.util.streamex.StreamEx;

// . . .

List<String> fullNames = StreamEx.zip(firstNames, surNames,
    (first, sur) -> first + " " + sur)
    .toList();

To use the StreamEx library you will have to add it as a dependency. For example, if you are using Maven:

<dependencies>
    <dependency>
        <groupId>one.util</groupId>
        <artifactId>streamex</artifactId>
        <version>0.8.1</version>
      </dependency>
</dependencies>

Alternatively, you can do the same thing with pure Java, but it is a little more verbose:

import java.util.stream.Collectors;
import java.util.stream.IntStream;

// . . .

List<String> fullNames = IntStream.range(0, Math.min(firstNames.size(), surNames.size()))
    .mapToObj(n -> firstNames.get(n) + " " + surNames.get(n))
    .collect(Collectors.toList());

If you are on Java 16 or later you can replace the last line with:

    .toList();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IOExeeption
Solution 2 Irfan_rahmani
Solution 3 Bohemian
Solution 4 David Conrad