Java Program to Merge two lists

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Merge two lists using addAll()

Output

First List: [2, 3, 5]
Second List: [4, 6]
Merged List: [2, 3, 5, 4, 6]

In the above example, have two lists named prime and even. Here, we have used the Java ArrayList addAll() method to add all elements from prime and even to the new list named numbers.


Example 2: Merge two lists using the Stream class

Output

First List: [2, 3, 5]
Second List: [4, 6]
Merged List: [2, 3, 5, 4, 6]

In the above example, we have used the Stream class to merge the two lists. Here,

  • stream() - converts the list into a stream
  • concat() - merges the two streams
  • collect(Collectors.toList()) - convert the stream into a list

To learn more about stream, visit Java Stream Class.