Thursday 29 June 2017

HashSet, TreeSet & LinkedHashSet

Set Collection:

Set is a type of collection that does not allow duplicate elements. That means an element can only exist once in a Set. Only one null value allowed in Set. Set is an Interface which extends Collections interface. 
Based on the characteristics, consider using a Set collection when:

  • You want to store elements distinctly without duplication, or unique elements.
  • You don’t care about the order of elements.
For example, you can use a Set to store unique integer numbers; For instance storing the student Ids which are unique etc. If you think there will be a chance of having duplicate values the Set is not your choice, chose List for this case.

There are three classes which implements Set interface. Let’s look at each implementation in details:
  • HashSet: is the best-performing implementation and is a widely-used Set implementation. It represents the core characteristics of sets: no duplication and unordered.
  • LinkedHashSet: This implementation orders its elements based on insertion order. So consider using a LinkedHashSet when you want to store unique elements in order.
  • TreeSet: This implementation orders its elements based on their values, either by their natural ordering, or by a Comparator provided at creation time.
Therefore, besides the uniqueness of elements that a Set guarantees, consider using HashSet when ordering does not matter; using LinkedHashSet when you want to order elements by their insertion order; using TreeSet when you want to order elements by their values.

Difference between HashSet, LinkedHashSet and TreeSet:





Let's explore above three Set implementation classes.

Creating a HashSet, LinkedHashSet or TreeSet in java:


Set<String> hashSet = new HashSet<>();
Set<String> linkedHashSet = new LinkedHashSet<>();
Set<String> treeSet = new TreeSet<>();

Creating HashSet, LinkedHashSet or TreeSet as easy as creating any variable in Java. But if you observe carefully we are assign all the Set classes to Set which is an Interface where HashSet, LinkedHashSet or TreeSet implements it. To know more about this please follow post Programming to Interfaces.

Apart from initialization or creating the different Sets, using all of it's methods are same. Means all HashSet, LinkedHashSet or TreeSet classes have very important methods in common as all of them implement same Interface called Set. So we use HashSet in all examples in this post to explore all the important methods.

Add Method:

Add an element to the Set.

Example:

import java.util.HashSet;
import java.util.Set;

public class SetDemo {

  public static void main(final String[] args) {
    // Create an HashSet and add two strings.
    final Set<String> set = new HashSet<>();
    set.add("Audi");
    set.add("BMW");
    System.out.println(set);
  }
}

Output:

[Audi, BMW]

addAll Method:
Appends all of the elements in the specified collection to the existing Set. Throws NullPointerException, if the specified collection is null.


import java.util.HashSet;
import java.util.Set;

public class SetDemo {

  public static void main(final String[] args) {
    final Set<String> set = new HashSet<>();
    set.add("Audi");
    set.add("BMW");
    set.add("Benz");
    System.out.println("Original Set: " + set);

    final Set<String> duplicate = new HashSet<>();
    //create a duplicate set from existing set
    duplicate.addAll(set);
    System.out.println("Duplicate Set: " + duplicate);
  }
}

Output:
Original Set: [Benz, Audi, BMW]
Duplicate Set: [Benz, Audi, BMW]

Get Method:
Because sets have no ordering. Some implementations do (particularly those implementing the java.util.SortedSet interface), but that is not a general property of sets.

If you're trying to use sets this way, you should consider using a list instead. So techincally there is no get method in Set.



size Method:

Returns the number of elements in this Set.


import java.util.HashSet;
import java.util.Set;
public class SetDemo { public static void main(final String[] args) { final Set<String> set = new HashSet<>(); set.add("Audi"); set.add("BMW"); set.add("Benz"); // print size of set System.out.println("Size of Set: " + set.size()); } } Output: Size of Set: 3


contains Method:

Searches whther a given element is present in the existing Set.
import java.util.HashSet;
import java.util.Set;
public class SetDemo { public static void main(final String[] args) { final Set<String> set = new HashSet<>(); set.add("Audi"); set.add("BMW"); set.add("Benz"); // Check set contains Audi System.out.println("Is set contain Audi: " + set.contains("Audi")); } } Output: Is set contain Audi: true


clear Method:

Removes all of the elements from the set. i.e. resets the set and size to 0.


isEmpty Method:

Check whether a set is empty means no elements in it. Returns true if empty or else false.

Let's use both clear and isEmpty methods in below example:

import java.util.HashSet;
import java.util.Set;
public class SetDemo { public static void main(final String[] args) { final Set<String> set = new HashSet<>(); set.add("Audi"); set.add("BMW"); set.add("Benz"); // print the current size of the Set System.out.println("The size of the LinkedList: " + set.size()); // Reset the Set using clear method set.clear(); System.out.println("Is Set empty: " + set.isEmpty()); } } Output: The size of the LinkedList: 3 Is Set empty: true


remove Method:

Removes the specific element in the Set. 


Note: removal will only possible with actual element value but not with index. Because sets have no ordering. Some implementations do (particularly those implementing the java.util.SortedSet interface), but that is not a general property of sets.


import java.util.HashSet;
import java.util.Set;
public class SetDemo { public static void main(final String[] args) { final Set<String> set = new HashSet<>(); set.add("Audi"); set.add("BMW"); set.add("Benz"); System.out.println("Original Set Elements" + set); // Removing BMW set.remove("BMW"); System.out.println("Set after removing BMW: " + set); } } Output: Original Set Elements[Audi, BMW, Benz] Set after removing BMW: [Audi, Benz]



toArray Method:

Returns an array containing all of the elements. Throws NullPointerException if the specified array is null.



import java.util.HashSet;
import java.util.Set;
public class SetDemo { public static void main(final String[] args) { final Set<String> set = new HashSet<>(); set.add("Audi"); set.add("BMW"); set.add("Benz"); Object[] array = set.toArray(); } }

Set as a Method Arguement: 

A Set can be passed as an argument to another method like in below example.


import java.util.HashSet;
import java.util.Set;

public class SetDemo {

  public static void printSet(final Set<String> set) {
    for (final String item : set) {
      System.out.println(item);
    }
  }

  public static void main(final String[] args) {
    final Set<String> set = new HashSet<>();
    set.add("Audi");
    set.add("BMW");
    set.add("Benz");

    printSet(set);
  }
}

Output:
Benz
Audi
BMW

Here:I have a method to print Set values that receives any Set implemented class variable as an argument. This method does not create new objects. So, this method can be reused whenever you want to print the values of a Set. Thus you are reducing the redundant code.





1 comment: