Here we can combine multiple lists in java 8 using the Stream API and flatMap() .
- First, we create three lists of Integer type data.
- Next, we create a stream of all lists by using the Stream.of() method.
- Then, we use flatMap() to convert all list elements into a single stream.
- After that, we use the collect() method to collect all integer values into one list.
- Finally, we print the complete data as a single list.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MulipleListAdd {
public static void main(String[] args) {
List list1 = Arrays.asList(2, 3, 4, 5);
List list2 = Arrays.asList(21, 31, 41, 51);
List list3 = Arrays.asList(20, 30, 40, 50);
List combinedList = Stream.of(list1, list2, list3)
.flatMap(list -> list.stream())
.collect(Collectors.toList());
System.out.println("All List of data :- " + combinedList);
}
}
Output :-
All List of data :- [2, 3, 4, 5, 21, 31, 41, 51, 20, 30, 40, 50]
FAQ
What does flatMap() do in Java 8?
flatMap() transforms each element into a stream and then flattens them into a single stream.
Can we combine lists without Stream API?
Yes, you can use addAll() method, but Stream API provides a cleaner and more functional approach.