Java TreeSet

TreeSet is one of the classes of the Java standard library. It is a subclass of the class AbstractSet and implements the interfaces Set<E>, SortedSet, NabigableSet, Collection<E>, Iterable<E>, Serializable, Cloneable.

The following UML diagram shows the position of the class TreeSet in the hierarchy.

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 

treeset-hierarchy

What is a TreeSet in Java?

A TreeSet is a data structure that allows you to collect elements. It is one of the classes in the Java library, which contains different methods to add, remove elements and more. To use it in your own classes, you need to import the package “java.util” from the Java library  as shown below.

import java.util.TreeSet;

Is TreeSet my best Java collection class choice?

To answer the question whether TreeSet is your best choice, you need to know more details about it as well as about other Java collection classes. The information and the exercises below will help you to make that decision.

  1. TreeSet implements Set as well as SortedSet interfaces.
  2. The elements of a TreeSet can be sorted.
  3. Adding a duplicate element to a TreeSet, results in overwriting the old element, because it does not allow duplicates.
  4. It doesn’t allow null value unlike HashSet.
  5. TreeSet is unsynchronized.

The following exercises show some important methods of what you can do with the elements of a TreeSet.

We use the same examples, which we already used in HashSet to find out the difference between those two.

Exercise 1A: How to create a Java TreeSet and add elements to it?

  • Create a TreeSet “nameSet” and add the following names to it: Nora, Thomas, Lily, Charles, David, Ella.

Exercise 1B: How to find the size of a Java TreeSet?

  • Print the size of the TreeSet to the standard output before and after adding the names.

Answer 1:

  • A- The following code adds the mentioned names to the TreeSet nameSet.
  • B- The program writes the following to the standard output when it is compiled and run.

nameSet size before adding the names: 0
nameSet size after adding the names: 6

import java.util.TreeSet;

public class TestTreeSet {

	public static void main(String[] args){

		TreeSet<String> nameSet = new TreeSet<String>();
		System.out.println("nameSet size before adding the names: " + nameSet.size());

		nameSet.add("Nora");
		nameSet.add("Thomas");
		nameSet.add("Lily");
		nameSet.add("Charles");
		nameSet.add("David");
		nameSet.add("Ella");
		System.out.println("nameSet size after adding the names: " + nameSet.size());
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 2: How to retrieve the elements of a Java TreeSet and print them to the standard output?

  • Add a piece of code to the exercise 1 to print all the names to the standard output.

Answer 2:

  • When the program is compiled and run, it writes the following names to the standard output.

Print the names to the standard output
Charles David Ella Lily Nora Thomas
Another method to print the names to the standard output
Charles David Ella Lily Nora Thomas

import java.util.Iterator;
import java.util.TreeSet;

public class TestTreeSet {

	public static void main(String[] args){

		TreeSet<String> nameSet = new TreeSet<String>();
		nameSet.add("Nora");
		nameSet.add("Thomas");
		nameSet.add("Lily");
		nameSet.add("Charles");
		nameSet.add("David");
		nameSet.add("Ella");

		System.out.println("Print the names to the standard output");
		Iterator<String> iter = nameSet.iterator();
		while(iter.hasNext()) {
			System.out.print(" " + iter.next());
		}
		System.out.println();
		System.out.println("Another method to print the names to the standard output");
		for(String temp:nameSet) {
			System.out.print(" " + temp);
		}
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 3: How to associate the contents of two TreeSets in one?

  • Create two TreeSets “group1” and “group2”.
  • Add the names “Olivia, Mia, Alexander, Mason, James” to the first group1.
  • Add the names “Joseph, Mia, Mila, Olivia, James, Charlotte” to the second group2.
  • Create a new TreeSet “allNames” and add both group names to it.

TreeSet doesn’t allow duplicates that is why it overwrites the duplicates automatically.

Answer 3:

  • When the program is compiled and run, it writes the following names to the standard output.
  • The names are in alphabetical order

Group1: [Alexander, James, Mason, Mia, Olivia]
Group2: [Charlotte, James, Joseph, Mia, Mila, Olivia]
Both Groups: [Alexander, Charlotte, James, Joseph, Mason, Mia, Mila, Olivia]

import java.util.Set;
import java.util.TreeSet;

public class TestTreeSet {

	public static void main(String args[]){

		Set group1,group2,bothGroups;
		group1 = new TreeSet();
		group2 = new TreeSet();

		group1.add("Olivia");
		group1.add("Mia");
		group1.add("Alexander");
		group1.add("Mason");
		group1.add("James");

		group2.add("Joseph");
		group2.add("Mia");
		group2.add("Mila");
		group2.add("Olivia");
		group2.add("James");
		group2.add("Charlotte");

		bothGroups = new TreeSet(group1);
		//The duplicates appear only ones
		bothGroups.addAll(group2);

		System.out.println("Group1:     " + group1);
		System.out.println("Group2:     " + group2);
		System.out.println("Both Groups:  " + bothGroups);
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 
Megisoft.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes. The author of Megisoft is Sar Maroof who has more than a decade of experience with web development mainly with Java, MySql, HTML and more..

Suggested Articles:


Sar Maroof's New Book "Java Quizmaster For Beginners"
Author: Sar Maroof
Many years of experience with developing web applications mainly with Java.
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster
Applied Science in Physics HBO Amsterdam
Bachellor Science in Physics at Basra university.
 Subscribe To sarmaroof RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

1 Comment

Add a Comment

Leave a Reply

megisoft © 2016