简体   繁体   中英

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]

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);
}

//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));
}

}

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

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM