Add elements to HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 16-Jan-2019 06:41:41
Advertisements