In this tutorial, we will learn how to add odd and even numbers into a single list in Java 8. Java 8 provides the Stream API , which allows us to combine multiple lists easily using the flatMap() method.
Code Explanation (Step-by-Step)
- First, we create three lists: EvenNumbers, PrimeNumbers, and OddNumbers.
- Then, we add all three lists into one parent list using List<List<Integer>>.
- After that, we use the stream() method to process the parent list.
- The flatMap() method converts each inner list into a single stream of integers.
- Finally, we use Collectors.toList() to collect all numbers into one list.
- The final list contains even, prime, and odd numbers together.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AddListData {
public static void main(String[] args) {
List evenNumbers = Arrays.asList(12, 14, 16, 18);
List primeNumbers = Arrays.asList(5, 7, 11, 13);
List oddNumbers = Arrays.asList(1, 3, 5);
List> numbersList = Arrays.asList(evenNumbers, primeNumbers, oddNumbers);
List combinedNumbers = numbersList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println("Add prime, odd and even numbers into list: " + combinedNumbers);
}
}
Output :-
Add prime, odd and even numbers into list: [12, 14, 16, 18, 5, 7, 11, 13, 1, 3, 5]
Java Program to Combine Multiple Lists Using Using addAll()
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CombineMultipleLists {
public static void main(String[] args) {
List evenNumbers = Arrays.asList(12, 14, 16, 18);
List primeNumbers = Arrays.asList(5, 7, 11, 13);
List oddNumbers = Arrays.asList(1, 3, 5);
List combinedList = new ArrayList<>();
combinedList.addAll(evenNumbers);
combinedList.addAll(primeNumbers);
combinedList.addAll(oddNumbers);
System.out.println("Combined list: " + combinedList);
}
}
FAQ
How do you combine multiple lists in Java 8?
You can combine multiple lists in Java 8 by using the Stream API with the flatMap() method. It converts multiple inner lists into a single stream and collects the result into one list.
Which Java 8 method is used to merge multiple lists?
The flatMap() method is commonly used to merge multiple lists into a single list in Java 8.
What is the use of Collectors.toList() in Java 8?
Collectors.toList() is used to collect stream elements into a new list.
Can we convert the final list into an array in Java 8?
Yes, we can convert the final list into an array by using the toArray() method.
Integer[] array = combinedList.toArray(new Integer[0]);