HashSet in java code example

Example 1: how to define an arraylist in java

ArrayList<Integer> integerArray = new ArrayList<Integer>();
ArrayList<String> integerArray = new ArrayList<String>();
ArrayList<Double> integerArray = new ArrayList<Double>();
//... keep replacing what is inside the <> with the appropriate
//data type

Example 2: 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 3: 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 4: hashset in java

// java hashmap example
import java.util.HashMap;
public class HashMapExample 
{
   public static void main(String[] args) 
   {
      HashMap<Integer, String> hm = new HashMap<Integer, String>();
      // add elements
      hm.put(10,"Apple");
      hm.put(20,"Banana");
      hm.put(30,"Cherry");
      hm.put(40,"Dragonfruit");
      // print HashMap elements
      System.out.println("HashMap elements: " + hm);
   }
}

Example 5: hashset in java

- HashSet can have null, order is not guaranteed

Example 6: hashset in java

// 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);
   }
}

Tags:

Java Example