Initialize HashSet in Java

Java Programming Java 8Object Oriented Programming

A set is a collection which does not allows duplicate values. HashSet is an implementation of a Set. Following are the ways in which we can initialize a HashSet in Java.

  • Using constructor − Pass a collection to Constructor to initialize an HashSet.

  • Using addAll() − Pass a collection to Collections.addAll() to initialize an HashSet.

  • Using unmodifiableSet() − Pass a collection to Collections.unmodifiableSet() to get a unmodifiable Set.

  • Using add() − Using add(element) method of Set.

Following is an example of using above ways.

Example

Infinity

Now consider the following code snippet.

Example

 Live Demo

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Tester{
   public static void main(String[] args) {

      List<Integer> list = Arrays.asList(1,2,3,4,5,6);
      //Scenario 1
      Set<Integer> set1 = new HashSet<>(list);
      System.out.println(set1);

      //Scenario 2
      Set<Integer> set2 = new HashSet<>(list);
      Collections.addAll(set2, 1,2,3,4,5,6);
      System.out.println(set2);

      //Scenario 3
      Set<Integer> set3 = Collections.unmodifiableSet(set2);
      System.out.println(set3);

      //Scenario 4
      Set<Integer> set4 = new HashSet<>();
      set4.add(1);set4.add(2);set4.add(3);
      set4.add(4);set4.add(5);set4.add(6);
      System.out.println(set4);
   }
}

Output

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
raja
Published on 19-Sep-2018 11:22:49
Advertisements