4 ways to Join two Lists in Java

In this post, we will see how to join two lists in Java using Plain Java, Java 8, Guava, and Apache Commons Collections. And try to cover most of it with an example.

1. Plain Java

⮚ List.addAll()

List interface provides addAll(Collection) the method that appends all elements of the specified collection to the end of the list. We can use it as and even this is included in Java.util package and we need not have to add any extra dependency:

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    List<T> list = new ArrayList<>();
 
    list.addAll(list1);
    list.addAll(list2);
 
    return list;
}

We can also initialize the result list by first list using ArrayList constructor, thereby preventing an extra call to addAll().

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
	List<T> list = new ArrayList<>(list1);
	list.addAll(list2);

	return list;
}

⮚ Double Brace Initialization

Using Double Brace Initialization which internally creates an anonymous inner class with an instance initializer in it.

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
	return new ArrayList<T>() {{
			addAll(list1);
			addAll(list2);
		}};
}

 
The technique should be best avoided as it costs an extra class for each user and it also holds hidden references and to the enclosing instance and to any captured objects. However, This may cause memory leaks or problems with serialization.

⮚ Collections.addAll()

Collections class provides several useful static utility methods that operate on collections. One such method is addAll(Collection, T[]) that adds all of the specified elements to the specified collection and this default added in Java.util package.

// Function to join two lists in Java
public static List<String> merge(List<String> list1, List<String> list2)
{
    List<String> list = new ArrayList<>();
 
    Collections.addAll(list, list1.toArray(new String[0]));
    Collections.addAll(list, list2.toArray(new String[0]));
 
    return list;
}

To sum up, this method is similar to List.addAll() but likely to run significantly faster.

2. Java 8

We can also use Java 8 Stream API to join two lists.

⮚ Stream.of() + flatMap() + Collector

Here we’re obtaining a stream consisting of elements from both the list using the static factory method Stream.of() and accumulating all elements into a new list using a Collector. However, this comes included with Java you need not add an extra dependency.

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
	return Stream.of(list1, list2)
				   .flatMap(x -> x.stream())
				   .collect(Collectors.toList());
}

⮚ Stream.of() + Stream.forEach()

We can avoid using a Collector by accumulating all elements using forEach() instead and follow the below example:

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
	List<T> list = new ArrayList<>();
	Stream.of(list1, list2).forEach(list::addAll);

	return list;
}

⮚ Stream.concat() + Collector

Stream provides concat() that takes two streams as input and creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream however it has its own drawbacks.

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    return Stream.concat(list1.stream(), list2.stream())
                   .collect(Collectors.toList());
}

⮚ List.addAll()

This is a slight variation of List.addAll() the approach discussed earlier by using streams in Java 8 and above but it’s not so recommended for complex logics:

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
	List<T> list = list1.stream().collect(Collectors.toList());
	list.addAll(list2);

	return list;
}

3. Guava

Guava Iterables class provides many static utility methods that operate on or return objects of type Iterable but it has its own fallbacks.

⮚ Iterables.concat()

concat() can be used to combine two iterables into a single iterable.

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    return Lists.newArrayList(Iterables.concat(list1, list2));
}

⮚ Iterables.addAll()

addAll() adds all elements in iterable to collection. We can use this in similar way as Collections's addAll() method.

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
    List<T> list = Lists.newArrayList();
 
    Iterables.addAll(list, list1);
    Iterables.addAll(list, list2);
 
    return list;
}

4. Apache Commons Collections

The easiest but also forgotten type is Apache Commons Collections ListUtils class provides union() method that takes two lists as an input and returns a new list containing the second list appended to the first list.

// Generic function to join two lists in Java
public static<T> List<T> merge(List<T> list1, List<T> list2)
{
	return ListUtils.union(list1, list2);
}

And also if you required any technology you want to learn, let us know below we will publish them in our site http://tossolution.com/

Like our page in Facebook and follow us for New technical information.

Leave a Reply

Your email address will not be published. Required fields are marked *