Check out example codes for "hashset in java". It will help you in understanding the concepts better.

Code Example 1

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

Code Example 2

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

Code Example 3

for (int i=0; i<arr.length; i++) 
{ 
    type var = arr[i];
    statements using var;
}

Code Example 4

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
public class Main {
   public static void main(String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("a");
      list.add("b");
      list.add("c");
      list.add("d");
      list.add("e");
      list.add("f");
      
      //On met la liste dans le désordre
      Collections.shuffle(list);
      System.out.println(list);
      
      //On la remet dans l'ordre
      Collections.sort(list);
      System.out.println(list);
      
      Collections.rotate(list, -1);
      System.out.println(list);
      
      //On récupère une sous-liste
      List<String> sub = list.subList(2, 5);
      System.out.println(sub);
      Collections.reverse(sub);
      System.out.println(sub);
      
      //On récupère un ListIterator
      ListIterator<String> it = list.listIterator();
      while(it.hasNext()){
         String str = it.next();
         if(str.equals("d"))
            it.set("z");
      }
      while(it.hasPrevious())
         System.out.print(it.previous());
      
   }
}

Code Example 5

// predefined HashSet class
public class HashSet
{
    // A HashMap object 
    private transient HashMap map;

    // A Dummy value(PRESENT) to associate with an Object in the Map
    private static final Object PRESENT = new Object();
    
    // default constructor of HashSet class
    // It creates a HashMap by calling 
    // default constructor of HashMap class
    public HashSet() {
        map = new HashMap<>();
    }

    // add method 
    // it calls put() method on map object
    // and then compares it's return value with null
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
 
    // Other methods in Hash Set
}

Code Example 6

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

Learn ReactJs, React Native from akashmittal.com