Algorithm
-
Input:
- Two lists:
list1
andlist2
of the same type.
- Two lists:
-
Output:
- A new list
joinedList
containing all elements fromlist1
andlist2
.
- A new list
-
Algorithm Steps:
- Create an empty list
joinedList
. - Iterate over each element in
list1
.- Add the current element to
joinedList
.
- Add the current element to
- Iterate over each element in
list2
.- Add the current element to
joinedList
.
- Add the current element to
- Create an empty list
-
Result:
- The
joinedList
now contains all elements from bothlist1
andlist2
.
- The
Code Examples
#1 Code Example- Join Two Lists using addAll()
Code -
Java Programming
import java.util.ArrayList;
import java.util.List;
public class JoinLists {
public static void main(String[] args) {
List < String> list1 = new ArrayList();
list1.add("a");
List < String> list2 = new ArrayList();
list2.add("b");
List < String> joined = new ArrayList();
joined.addAll(list1);
joined.addAll(list2);
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("joined: " + joined);
}
}
Copy The Code &
Try With Live Editor
Output
list1: [a]
list2: [b]
joined: [a, b]
list2: [b]
joined: [a, b]
#2 Code Example- Join Two Lists using union()
Code -
Java Programming
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;
public class JoinLists {
public static void main(String[] args) {
List < String> list1 = new ArrayList();
list1.add("a");
List < String> list2 = new ArrayList();
list2.add("b");
List < String> joined = ListUtils.union(list1, list2);
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("joined: " + joined);
}
}
Copy The Code &
Try With Live Editor
#3 Code Example- Join Two Lists using stream
Code -
Java Programming
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JoinLists {
public static void main(String[] args) {
List < String> list1 = new ArrayList();
list1.add("a");
List < String> list2 = new ArrayList();
list2.add("b");
List < String> joined = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("joined: " + joined);
}
}
Copy The Code &
Try With Live Editor
Demonstration
Java Programing Example to Join Two Lists-DevsEnv