How to join or merge two lists efficiently in Java?

In Java, the List<E> is an interface. By using this interface we can store ordered collection. So, List is an ordered collection of objects that can store duplicate values.

Now if we have two lists that we want to merge. We can achieve this in many ways. Following are some efficient ways to join or merge two lists in Java:

By using stream

List firstList = Arrays.asList("Sweden", "Denmark");
List secondList = Stream.of("France", "Germany").collect(Collectors.toList());
List combinedList = Stream.concat(firstList.stream(), secondList.stream())
     .collect(Collectors.toList());

Initialize and addAll

List firstList = Arrays.asList("Sweden", "Denmark");
List secondList = Stream.of("France", "Germany").collect(Collectors.toList());
List combinedList = new ArrayList(firstList);
combinedList.addAll(secondList);

Source:
Join two lists in Java

Share