Piano Guidance
Photo by Katrīne Žuka Pexels Logo Photo: Katrīne Žuka

Which is faster TreeSet or HashSet?

HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data.

Why should kids take piano lessons?
Why should kids take piano lessons?

Learning to play the piano can increase your child's confidence and their ability to concentrate and maintain focus. It allows them to practice...

Read More »
Is it harder to sing when fat?
Is it harder to sing when fat?

Specifically, the pitch gets slightly lower. More importantly, obese people are often not in good physical condition. This often results in poor...

Read More »

When it comes to discussing differences between Set the firstmost thing that comes into play is the insertion order and how elements will be processed. HashSet in java is a class implementing the Set interface, backed by a hash table which is actually a HashMap instance. This class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets while TreeSet is an implementation of the SortedSet interface which as the name suggests uses the tree for storage purposes where here the ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided.

1. Speed and internal implementation

For operations like search, insert, and delete HashSet takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(Log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a self-balancing binary search tree (Red-Black Tree). TreeSet is backed by TreeMap in Java.

2. Ordering

Elements in HashSet are not ordered. TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java. TreeSet elements are sorted in ascending order by default. It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.

3. Null Object

HashSet allows null object. TreeSet doesn’t allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException.

4. Comparison

HashSet uses the equals() method to compare two objects in Set and for detecting duplicates. TreeSet uses compareTo() method for same purpose. If equals() and compareTo() are not consistent, i.e. for two equal objects equals should return true while compareTo() should return zero, then it will break the contract of Set interface and will allow duplicates in Set implementations like TreeSet Note: If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it.

Geek after going through their differences now you must be wondering when to prefer TreeSet over HashSet?

Sorted unique elements are required instead of unique elements. The sorted list given by TreeSet is always in ascending order. TreeSet has a greater locality than HashSet.If two entries are nearby in the order, then TreeSet places them near each other in data structure and hence in memory, while HashSet spreads the entries all over memory regardless of the keys they are associated to. TreeSet uses a Red-Black tree algorithm underneath to sort out the elements. When one needs to perform read/write operations frequently, then TreeSet is a good choice. LinkedHashSet is another data structure that is between these two. It provides time complexities like HashSet and maintains the order of insertion (Note that this is not sorted order, but the order in which elements are inserted).

Is Pianote lifetime membership worth it?
Is Pianote lifetime membership worth it?

Pianote is definitely worth it for beginners looking for a comprehensive method to get playing quickly. It would also be very useful for...

Read More »
How do I keep my piano keys from sticking?
How do I keep my piano keys from sticking?

To try and fix this issue, the key that is causing problems needs to be depressed firmly but slowly and gently moved from side to side whilst...

Read More »

Implementation: Here we will be discussing them both with 2 examples for both of them. Let us start with HashSet later on dwelling on to TreeSet.

HashSet examples

TreeSet examples

Example 1:

Java

import java.util.HashSet; class GFG { public static void main(String[] args) { HashSet hset = new HashSet(); hset.add( "geeks" ); hset.add( "for" ); hset.add( "practice" ); hset.add( "contribute" ); hset.add( "geeks" ); System.out.println( "HashSet contains: " ); for (String temp : hset) { System.out.println(temp); } } }

Output: HashSet contains: practice geeks for contribute

Example 2:

Java

import java.util.*; class GFG { public static void main(String[] args) { ArrayList ll = new ArrayList(); ll.add( "Computer" ); ll.add( "Science" ); HashSet hs = new HashSet(ll); hs.add( "Portal" ); hs.add( "GFG" ); Iterator iter = hs.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } }

Output:

Now it’s time to implement TreeSet to understand better via implementing it.

Example 1:

Java

import java.util.TreeSet; class TreeSetDemo { public static void main(String[] args) { TreeSet tset = new TreeSet(); tset.add( "geeks" ); tset.add( "for" ); tset.add( "practice" ); tset.add( "contribute" ); tset.add( "geeks" ); System.out.println( "TreeSet contains: " ); for (String temp : tset) { System.out.println(temp); } } }

Output: TreeSet contains: contribute for geeks practice

Example 2:

Java

import java.util.*; class GFG { public static void main(String[] args) { ArrayList ll = new ArrayList(); ll.add( "Computer" ); ll.add( "Science" ); TreeSet ts = new TreeSet(ll); ts.add( "Portal" ); ts.add( "GFG" ); Iterator iter = ts.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } }

Output:

What happens to your brain when you play piano?
What happens to your brain when you play piano?

Benefits of Playing the Piano: Neuroplasticity Playing the piano changes the brain in a positive way! Studies show that music stimulates the brain...

Read More »
Does vinegar remove tarnish from metal?
Does vinegar remove tarnish from metal?

1. For tarnished brass or copper: in a plastic or glass container, dilute 1 Tbsp of a weak acid (vinegar or lemon juice) in 4 cups water and add 1...

Read More »
What is the oldest instrument still used today?
What is the oldest instrument still used today?

Neanderthal Flute Archaeologists have found a pre-historic instrument carved from cave bear bones, and it can still be played today. The...

Read More »
Join almost HALF A MILLION Happy Students Worldwide
Join almost HALF A MILLION Happy Students Worldwide

Pianoforall is one of the most popular online piano courses online and has helped over 450,000 students around the world achieve their dream of playing beautiful piano for over a decade.

Learn More »
Did the Beatles ever use power chords?
Did the Beatles ever use power chords?

I Want to Hold Your Hand - 1963. Recorded and released on Meet the Beatles!, the song's opening riff uses a couple of power chords, or 5th chords.

Read More »