Initializing HashSet in Java

Java 8Object Oriented ProgrammingProgramming

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.

A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.

Following is an example to initialize a HashSet with string elements −

Example

 Live Demo

import java.util.*;
public class Main {
   public static void main(String[] args) {
      String str[] = { "Tom", "Jack", "Katie", "Tim" };
      Set<Integer> set = new HashSet(Arrays.asList(str));
      System.out.println("HashSet elements = "+set);
   }
}

Output

HashSet elements = [Tom, Katie, Tim, Jack]

Let us see another example −

Example

import java.util.*;
public class Main {
   public static void main(String args[]) {
      Set<String> hashSet = new HashSet<String>();
      hashSet.add("green");
      hashSet.add("blue");
      hashSet.add("red");
      hashSet.add("cyan");
      hashSet.add("orange");
      hashSet.add("green");
      System.out.println("HashSet elements\n"+ hashSet);
      Set<String> treeSet = new TreeSet<String>(hashSet);
      System.out.println("Sorted elements\n"+ treeSet);
   }
}

Output

HashSet elements
[red, orange, green, blue, cyan]
Sorted elements
[blue, cyan, green, orange, red]
raja
Published on 20-Sep-2019 11:36:00
Advertisements