Get Union & Intersection of Two TreeSet in Java (Set)

This example shows how to get a union or intersection of two TreeSet objects in Java. This example also shows how to get a union and intersection of two Sets using the retainAll and addAll methods.

How to get a union or intersection of two TreeSet (Set) objects in Java?

How to get a union of two Set objects (TreeSet objects)?

The union of two Set objects is a Set of all elements present in the two Set objects like a TreeSet. The union of Sets is also a Set so it does not have duplicate elements. For example, if set 1 contains [1, 2, 3] and set 2 contains [2, 3, 4] then the union of these two sets will be [1, 2, 3, 4].

We can get a union of two TreeSet objects using the addAll method.

The addAll method adds all the elements of the specified collection object to this set. If the specified collection has elements that are already present in this set, they are not added.


As we can see from the output, the element “3” was not added because it was already present in the TreeSet.

How to get an intersection of two Set objects (TreeSet objects)?

The intersection of two sets A and B is the set of all elements of set A that are also present in the set B. In other words, its the set containing all common elements of the given two sets.

For example, the intersection of set [1, 2, 3] and set [2, 3, 4] is [2, 3] i.e. common elements of set 1 and set 2.

We can get the intersection of two Set objects (TreeSet objects) using the retainAll method.

The retainAll method removes all elements from this set that are not present in the specified collection. In other words, all the common elements of this set and the specified collection object are kept in this set object, other elements are removed.


This example is a part of the TreeSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 TreeSet

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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

Online Shopping