Home > Blockchain >  merge two array list in java with specific order
merge two array list in java with specific order

Time:04-21

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]

CodePudding user response:

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

CodePudding user response:

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

}

CodePudding user response:

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

list1.replaceAll(s -> s   " "   list2.remove(0));
  •  Tags:  
  • java
  • Related