what is hashset in java code example

Example 1: how to push an element in hashset java

HashSet<Integer> set=new HashSet<>();
//adding a new element
set.add(10);

Example 2: hashset in java

// iterate hashset in java
import java.util.HashSet;
public class HashSetForEach 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Hello"); 
      hs.add("world"); 
      hs.add("Java"); 
      for(String str : hs)
      {
         System.out.println(str);
      }
   }
}

Example 3: hashset in java

Let’s see java hashset example.

import java.util.HashSet;
public class HashSetExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<>();
      hs.add("Banana");
      hs.add("Orange");
      hs.add("Apple");
      hs.add("Pineapple");
      hs.add("Mango");
      System.out.println(hs);
   }
}

Example 4: java hashset

HashSet<String> hset = new HashSet<String>();
// Adding elements to the HashSet
hset.add("Apple");
hset.add("Mango");

Example 5: what is hashset in java

- HashSet can have null, order is not guaranteed

Example 6: HashSet h = new HashSet();

HashSet<String> h = new HashSet<String>();

Tags:

Java Example