Union of ArrayList Java

Are there any methods to do so? I was looking but couldn’t find any.

Another question: I need these methods so I can filter files. Some are AND filters and some are OR filters (like in set theory), so I need to filter according to all files and the unite/intersects ArrayLists that holds those files.

Should I use a different data structure to hold the files? Is there anything else that would offer a better runtime?

Answer

Here’s a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don’t modify the original lists input to the methods.

public class Test { public static void main(String... args) throws Exception { List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C")); List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F")); System.out.println(new Test().intersection(list1, list2)); System.out.println(new Test().union(list1, list2)); } public <T> List<T> union(List<T> list1, List<T> list2) { Set<T> set = new HashSet<T>(); set.addAll(list1); set.addAll(list2); return new ArrayList<T>(set); } public <T> List<T> intersection(List<T> list1, List<T> list2) { List<T> list = new ArrayList<T>(); for (T t : list1) { if(list2.contains(t)) { list.add(t); } } return list; } }

Given two ArrayLists in Java, the task is to join these ArrayLists.

Examples:

Input: ArrayList1: [Geeks, For, ForGeeks], ArrayList2: [GeeksForGeeks, A computer portal]
Output: ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]

Input: ArrayList1: [G, e, e, k, s], ArrayList2: [F, o, r, G, e, e, k, s]
Output: ArrayList: [G, e, e, k, s, F, o, r, G, e, e, k, s]

Approach: ArrayLists can be joined in Java with the help of Collection.addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

Syntax:

ArrayList1.addAll(ArrayList2);

Below is the implementation of the above approach:

import java.util.*;

public class GFG {

    public static void main(String args[])

    {

        ArrayList<String>

            list1 = new ArrayList<String>();

        list1.add("Geeks");

        list1.add("For");

        list1.add("ForGeeks");

        System.out.println("ArrayList 1: "

                           + list1);

        ArrayList<String>

            list2 = new ArrayList<String>();

        list2.add("GeeksForGeeks");

        list2.add("A computer portal");

        System.out.println("ArrayList 2: "

                           + list2);

        list1.addAll(list2);

        System.out.println("Joined ArrayLists: "

                           + list1);

    }

}


Practice Tags :

Learn how to merge two arraylists into a combined single arraylist in Java. Also learn to join arraylists without duplicates in the combined list.

1. Merge arraylists – List.addAll() method

addAll() method simplest way to append all of the elements in the given collection to the end of another list. Using this method, we can combine multiple lists into a single list.

import java.util.ArrayList; import java.util.Arrays; public class ArrayListExample { public static void main(String[] args) throws Exception { ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "f")); ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); listOne.addAll(listTwo); //Merge both lists System.out.println(listOne); } }

Program output.

[a, b, c, d, e, a, b, c, f, g]

TIP : There are more ways to merge lists using libraries like guava or Apache commons lang, but they all use addAll() method only. So it’s better to use this method directly.

2. Merge arraylists – Java 8 Stream.flatMap()

Java 8 streams provide us one line solutions to most of the problems and at same time, the code looks clean. Stream’s flatMap() method can be used to get the elements of two or more lists in single stream, and then collect stream elements to an arraylist.

import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ArrayListExample { public static void main(String[] args) throws Exception { ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "f", "g")); List<String> combinedList = Stream.of(listOne, listTwo) .flatMap(x -> x.stream()) .collect(Collectors.toList()); System.out.println(combinedList); } }

Program output.

[a, b, c, d, e, a, b, c, f, g]

3. Merge two arraylists without duplicates

In first two examples, we combined the lists but in final list we had duplicate elements. This may not be a desired output in many cases.

To get combined list minus duplicate elements, we have two approaches:

  1. Use LinkedHashSet. A set allow only unique elements. Push both lists in a set and set will represent a list of all unique elements combined.

    We are using LinkedHashSet because it will preserve the elements order as well.

  2. This is two step process. Remove all elements of first list from second list, and then add first list to second list. It will give use the combined list without duplicate elements.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class ArrayListExample { public static void main(String[] args) throws Exception { ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "f", "g")); //1 Set<String> set = new LinkedHashSet<>(listOne); set.addAll(listTwo); List<String> combinedList = new ArrayList<>(set); System.out.println(combinedList); //2 List<String> listTwoCopy = new ArrayList<>(listTwo); listTwoCopy.removeAll(listOne); listOne.addAll(listTwoCopy); System.out.println(listOne); } }

Program output.

[a, b, c, d, e, f, g] [a, b, c, d, e, f, g]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Let us know if you liked the post. That’s the only way we can improve.

List of utility methods to do ArrayList Union

The list of methods to do ArrayList Union are organized into topic(s).

ArrayListunion(ArrayList list1, ArrayList list2)
union ArrayList<String> result = new ArrayList<String>(); result.addAll(list1); result.addAll(list2); Collections.sort(result); return distinct(result);
ArrayListUnion(ArrayList list1, ArrayList list2)
Finds the union of two lists of String objects Set union = new HashSet(list1); union.addAll(new HashSet(list2)); return new ArrayList(union);
ArrayListunion(ArrayList a, ArrayList b)
union ArrayList<T> result = new ArrayList<T>(); for (T t : a) if (!result.contains(t)) result.add(t); for (T t : b) if (!result.contains(t)) result.add(t); return result; ...
ArrayListunionSets(ArrayList s1, ArrayList s2)
union two sets s1 and s2 if (s2 == null) { return s1; for (Integer i : s2) { if (!s1.contains(i)) { s1.add(i); return s1;