Introduction
Merging two lists is a common operation in Java, especially when you want to combine data from different sources or consolidate lists for further processing. With Java 8 Streams, merging lists has become more concise and efficient, allowing you to handle this task in a functional programming style. This guide will explore how to merge two lists using Java 8 Streams, including handling duplicates, different types of lists, and customizing the merged result.
Problem Statement
The task is to create a Java program that:
- Accepts two lists of elements.
- Merges the two lists into one.
- Outputs the merged list.
Example 1:
- Input: List 1:
["apple", "banana"], List 2:["orange", "mango"] - Output:
["apple", "banana", "orange", "mango"]
Example 2:
- Input: List 1:
[1, 2, 3], List 2:[4, 5, 6] - Output:
[1, 2, 3, 4, 5, 6]
Solution Steps
- Input Lists: Start with two lists of elements that can either be hardcoded or provided by the user.
- Merge the Lists Using Streams: Use the
Stream.concat()method to combine the lists into one. - Display the Result: Print the merged list.
Java Program
Merging Lists of Strings Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Java 8: Merge Two Lists of Strings Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class MergeListsStrings {
public static void main(String[] args) {
// Step 1: Take input lists
List<String> list1 = Arrays.asList("apple", "banana");
List<String> list2 = Arrays.asList("orange", "mango");
// Step 2: Merge the lists using streams
List<String> mergedList = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Merged List: " + mergedList);
}
}
Output
Merged List: [apple, banana, orange, mango]
Explanation
In this example, two lists of strings, list1 and list2, are merged using the Stream.concat() method. The combined stream is collected into a new list using collect(Collectors.toList()). The result is a single list containing all elements from both input lists, in the order they were added.
Merging Lists of Integers Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Java 8: Merge Two Lists of Integers Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class MergeListsIntegers {
public static void main(String[] args) {
// Step 1: Take input lists
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);
// Step 2: Merge the lists using streams
List<Integer> mergedList = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Merged List: " + mergedList);
}
}
Output
Merged List: [1, 2, 3, 4, 5, 6]
Explanation
This example merges two lists of integers using the same approach as the previous example. The Stream.concat() method combines the elements of list1 and list2, and the resulting stream is collected into a new list. The output is a single list that includes all numbers from both input lists in sequence.
Merging Lists of Custom Objects Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Java 8: Merge Two Lists of Custom Objects Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class MergeListsCustomObjects {
public static void main(String[] args) {
// Step 1: Take input lists of custom objects
List<Student> list1 = Arrays.asList(
new Student("Raj", 25),
new Student("Anita", 30)
);
List<Student> list2 = Arrays.asList(
new Student("Vikram", 22),
new Student("Sita", 28)
);
// Step 2: Merge the lists using streams
List<Student> mergedList = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());
// Step 3: Display the result
mergedList.forEach(student ->
System.out.println(student.getName() + ": " + student.getAge())
);
}
}
// Custom class Student
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Output
Raj: 25
Anita: 30
Vikram: 22
Sita: 28
Explanation
In this example, two lists of custom Student objects are merged. Each list contains Student objects with a name and age property. The Stream.concat() method is used to merge the two lists, and the combined list is then iterated over to print each student’s name and age. The result is a single list that contains all students from both input lists.
Advanced Considerations
-
Handling Duplicates: If the lists being merged contain duplicate elements and you want to remove them, you can use
distinct()after merging the streams:List<String> mergedList = Stream.concat(list1.stream(), list2.stream()) .distinct() .collect(Collectors.toList()); -
Merging Different Types of Lists: If the lists are of different types (e.g.,
List<String>andList<Integer>), you can use generic types and casting where necessary, but typically, merging lists of different types is handled by transforming one or both lists to a common type. -
Performance Considerations: Merging large lists using Streams is efficient and leverages Java’s parallel processing capabilities if required. However, be aware of potential memory usage if the lists are extremely large.
Conclusion
This guide provides multiple methods for merging two lists using Java 8 Streams, covering lists of strings, integers, and custom objects like Student. Java 8 Streams offer a powerful and concise way to combine lists, making your code more readable and maintainable. Depending on your specific use case, you can apply the techniques demonstrated in this guide to achieve the desired result.