How do I combine two Lists in Java?
The output so far is:
Firstname1
Firstname2
Firstname3
Lastname1
Lastname2
Lastname3
[[Firstname1, Firstname2, Firstname3], [Lastname1, Lastname2, Lastname3]]
I want the out put to be:
[Firstname1 Lastname1, Firstname2 Lastname2, Firstname3 Lastname3}
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
List<String> peoplFname = Arrays.asList("Firstname1", "Firstname2", "Firstname3");
List<String> peoplLname = Arrays.asList("Lastname1", "Lastname2", "Lastname3");
Iterator<String> iterator = peoplFname.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
Iterator<String> iteratorx = peoplLname.iterator();
while(iteratorx.hasNext()) {
System.out.println(iteratorx.next());
}
HashSet peopleFullName = new HashSet();
peopleFullName.add(peoplFname);
peopleFullName.add(peoplLname);
System.out.println(peopleFullName.toString());
}
}
Use
addAllinstead ofadd, in order to add all elements from the list into your set.Change your code to:
Update:
Based on the updated question, it looks like you want to combine corresponding elements from both lists. You’re on the right track. You just need to iterate over both lists, join the first name with the last name and then add it to a result list: