Merging Lists in Java: A Comprehensive Guide

Method 1: Using the addAll() Method

Let’s start with a simple example. Suppose we have two lists, prime and even, and we want to merge them into a new list called numbers. We can achieve this using the addAll() method, which adds all elements from one list to another.


List<Integer> prime = Arrays.asList(2, 3, 5, 7);
List<Integer> even = Arrays.asList(2, 4, 6, 8);
List<Integer> numbers = new ArrayList<>();

numbers.addAll(prime);
numbers.addAll(even);

System.out.println(numbers); // Output: [2, 3, 5, 7, 2, 4, 6, 8]

Method 2: Using the Stream Class

The Stream class provides a more modern and flexible way to merge lists. By converting each list to a stream, we can concatenate them and collect the result into a new list.


List<Integer> prime = Arrays.asList(2, 3, 5, 7);
List<Integer> even = Arrays.asList(2, 4, 6, 8);
List<Integer> numbers = Stream.concat(prime.stream(), even.stream())
       .collect(Collectors.toList());

System.out.println(numbers); // Output: [2, 3, 5, 7, 2, 4, 6, 8]

Understanding the Stream Class

If you’re new to the Stream class, don’t worry! It’s a powerful tool that allows you to process data in a more functional programming style. To learn more about the Stream class and its capabilities, check out our dedicated resource on Java Stream Class.

By mastering these two methods, you’ll be able to merge lists with ease and take your Java skills to the next level. Whether you’re working on a small project or a large-scale application, understanding how to combine lists efficiently is an essential skill to have in your toolkit.

Leave a Reply