Add elements to HashSet in Java


First, create a HashSet −

HashSet hs = new HashSet();

Now, add some elements using the add() method. Set the elements as a parameter. Here, we have set string −

hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");

The following is an example to add elements to a HashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println(hs);
   }
}

Output

[A, B, C, D, E, F, K, M, N]

Updated on: 30-Jul-2019

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements