create a set java code example

Example 1: java create a set with values

Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c"));

Example 2: set java

import java.util.*;
public class SetDemo {

  public static void main(String args[]) { 
      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);

         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("The sorted list is:");
         System.out.println(sortedSet);

         System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
         System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
      }
      catch(Exception e) {}
   }
} 

OUTPUT:

              [34, 22, 10, 60, 30]
              The sorted list is:
              [10, 22, 30, 34, 60]
              The First element of the set is: 10
              The last element of the set is: 60

Example 3: java how to make set

//Creating HashSet 
HashSet<String> set = new HashSet(); 

//adding elements  
set.add("One");    
set.add("Two");    

//Removing element);
set.remove("One"); 

//Removing all the elements available in the set  
set.clear();

Example 4: set in java

SET: Can only store unique values, 
     And does not maintain order
- HashSet can have null, order is not guaranteed
- LinkedHashSet can have null and keeps the order 
- TreeSet sorts the order and don't accept null

Example 5: how to check how many elements in a set java

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/*
check a set size by set.size()
*/

public class MainClass {
  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));

    System.out.println(set.size());
  }
}

Tags:

Java Example