Java
Programming
List Manipulation
Coding
Software Development

How do I join two lists in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Java, lists are a part of the Java Collections Framework and are used to store an ordered collection of elements. There are multiple ways to join or combine two lists depending on the specific requirements and the type of lists used. The most common implementations of lists in Java are ArrayList and LinkedList. Each has its own characteristics suitable for different scenarios. Below, I'll discuss the various methods to join two lists and provide technical explanations and examples for each.

1. Using addAll() Method

The addAll() method is part of the List interface and is used to append all elements from one list to another. It ensures that the elements are added in the order they appear in the source list. Here's how you can use it:

java
1import java.util.ArrayList;
2import java.util.List;
3
4public class ListJoiner {
5    public static void main(String[] args) {
6        List<String> list1 = new ArrayList<>();
7        list1.add("Apple");
8        list1.add("Banana");
9
10        List<String> list2 = new ArrayList<>();
11        list2.add("Orange");
12        list2.add("Pineapple");
13
14        list1.addAll(list2);
15
16        System.out.println("Joined list: " + list1);
17    }
18}

2. Using Java 8 Streams

If you're using Java 8 or higher, Stream API provides a more modern and functional approach:

java
1import java.util.ArrayList;
2import java.util.List;
3import java.util.stream.Collectors;
4import java.util.stream.Stream;
5
6public class ListJoiner {
7    public static void main(String[] args) {
8        List<String> list1 = new ArrayList<>();
9        list1.add("Apple");
10        list1.add("Banana");
11
12        List<String> list2 = new ArrayList<>();
13        list2.add("Orange");
14        list2.add("Pineapple");
15
16        List<String> joinedList = Stream.concat(list1.stream(), list2.stream())
17                                        .collect(Collectors.toList());
18
19        System.out.println("Joined list: " + joinedList);
20    }
21}

This method is particularly useful when you need to perform additional stream operations such as filtering or mapping.

3. Using Apache Commons Collections

If you are already using Apache Commons Collections, it provides utility methods to manipulate collections:

java
1import org.apache.commons.collections4.ListUtils;
2import java.util.ArrayList;
3import java.util.List;
4
5public class ListJoiner {
6    public static void main(String[] args) {
7        List<String> list1 = new ArrayList<>();
8        list1.add("Apple");
9        list1.add("Banana");
10
11        List<String> list2 = new ArrayList<>();
12        list2.add("Orange");
13        list2.add("Pineapple");
14
15        List<String> joinedList = ListUtils.union(list1, list2);
16
17        System.out.println("Joined list: " + joinedList);
18    }
19}

4. Manual Iteration and Addition

Though not as efficient or elegant, manually iterating through each list and adding elements to another is always an option:

java
1import java.util.ArrayList;
2import java.util.List;
3
4public class ListJoiner {
5    public static void main(String[] args) {
6        List<String> list1 = new ArrayList<>();
7        list1.add("Apple");
8        list1.add("Banana");
9
10        List<String> list2 = new ArrayList<>();
11        list2.add("Orange");
12        list2.add("Pineapple");
13
14        List<String> joinedList = new ArrayList<>(list1);
15
16        for (String item : list2) {
17            joinedList.add(item);
18        }
19
20        System.out.println("Joined list: " + joinedList);
21    }
22}

Comparisons and Key Points

Here's a summary table of each method:

MethodDescriptionProsCons
addAll()Directly appends all elements from one list to another.Easy to use, modifies in-place.Modifies the original list.
Java 8 StreamsUses functional programming features to join lists.Flexible, doesn't modify originalSlightly complex syntax
Apache Commons CollectionsUtilities for common collections tasks.Simplifies code, safe operationsExternal dependency required
Manual IterationManually iterate and add elements from one list to another.Full control over processVerbose, error-prone

Performance Considerations

When joining lists, especially large ones, it's important to consider the performance implications:

  • addAll(): Efficient for small to medium lists. Performance may degrade with very large lists due to resizing.
  • Streams: Generally slower than direct manipulation methods like addAll() due to additional overhead but provides benefits of functional programming and immutability.
  • Apache Commons Collections: Similar performance to addAll() but with additional methods for specific cases.
  • Manual Iteration: Least efficient, especially for large lists.

Conclusion

The method you choose to join lists in Java can depend on many factors like Java version, performance considerations, and whether you prioritize readability or efficiency. Stream API is preferred for modern Java applications, whereas addAll() serves well in most straightforward scenarios. Using third-party libraries like Apache Commons offers additional utilities when you're handling complex collections operations frequently.


Course illustration
Course illustration

All Rights Reserved.