我有三个arraylist,这里我必须连接2个arraylist并将其显示到第三个arraylist中。下面是我的编码,
编码::
List<String> firstName = new ArrayList<String>();
List<String> lastName = new ArrayList<String>();
/////inserting first name
String string1 = "aaa";
firstName.add(string1);
String string2 = "bbb";
firstName.add(string2);
///////inserting last name
String string3 = "yyy";
lastName.add(string3);
String string4 = "zzz";
lastName.add(string4);
/////////first name
Iterator<String> iterator = firstName.iterator();
while(iterator.hasNext()){
String FirstName = iterator.next();
System.out.println(" FirstName "+FirstName);
}
//////////////last name
Iterator<String> iterator1 = lastName.iterator();
while(iterator1.hasNext()){
String LastName = iterator1.next();
System.out.println(" LastName "+LastName);
}
List<String> name=new ArrayList<String>();
///////////name=firstname+lastname
Iterator<String> iterator11 = lastName.iterator();
while(iterator11.hasNext()){
name=firstName+lastName;///////here getting error
////////////what should I do here to add two arraylist<String> value
System.out.println(" Name = FirstName+LastName "+name);
}
我想要的输出:
FirstName aaa
FirstName bbb
LastName yyy
LastName zzz
Name = FirstName+LastName aaayyy
Name = FirstName+LastName bbbzzz
但是我不知道如何连接两个arrayList并将其显示在第三个arrayList中,请帮助我..在此先感谢..
最佳答案
如果列表大小相等,则可以一起迭代它们:
Iterator<String> iterator = firstName.iterator();
Iterator<String> iterator1 = lastName.iterator();
while(iterator.hasNext() && iterator1.hasNext()){
String FirstName = iterator.next();
String LastName = iterator1.next();
// add FirstName and LastName to the new list here
}
更新
Iterator<String> iterator = firstName.iterator();
Iterator<String> iterator1 = lastName.iterator();
List<String> newList = new ArrayList<String>();
while(iterator.hasNext() && iterator1.hasNext()){
String FirstName = iterator.next();
String LastName = iterator1.next();
newList.add(FirstName + " " + LastName);
}