Author
Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

Java Set

Published in the Java Collections group
members
Set is an interface in the Java Collection Framework. You can use Java Set to implement unordered collections with unique elements. In this article, we are going to look at this interface and its implementations in the Java language, methods for working with a set, and also give some examples.

What is Java Set

Set is an interface from the Java Collection Framework, but Set is not an ordered collection, unlike List. That means that Java Set elements are kept without a particular order. So there is no control over the position where you can insert an element. Also you can't access elements by their index. Mathematically, a Set is a collection of unique elements. In fact, this is an unordered Collection (unordered Collection), in which identical elements cannot be stored. If you intentionally add a duplicate element to a Set, this action will be ignored and the Set will not change. However it is permissible to store one null element in it.

Set implementations

Java Set is an interface, so you need to use one of its implementations to create objects. These are HashSet, TreeSet and LinkedHashSet. In Sets, each element is stored in only one instance, and different implementations of Set use a different order for storing elements. In a HashSet, the order of elements is determined by a complex algorithm. If storage order is important to you, use a TreeSet container, which stores objects sorted in ascending order in comparison order, or a LinkedHashSet, which stores elements in addition order. Sets are often used for membership testing so that you can easily check if an object belongs to a given set, so in practice a HashSet implementation that is optimized for fast lookup is usually chosen. HashSet is a collection that uses their hash values ​​returned by the hashCode() method to store elements internally. That is, inside the HashSet<E>, the HashMap<E, Object> object is stored, which stores the values ​​of the HashSet as keys. Using hash codes allows you to quickly search, add and remove elements from a Set. LinkedHashSet is a HashSet that also stores elements in a linked list. A normal HashSet does not maintain element order. Firstly, officially it simply does not exist, and secondly, even the internal order can change dramatically when just one element is added. And you can get an iterator from LinkedHashSet and use it to go through all the elements in the exact order in which they were added to the LinkedHashSet. Not often, but sometimes it can be very necessary. A TreeSet is a collection that stores elements as a value-ordered tree. Inside the TreeSet<E> is a TreeMap<E, Object> that stores all these values. And this TreeMap uses a red-black balanced binary tree to store elements. Therefore, it has very fast add(), remove(), contains() operations.

Create a Set Object

To create a Set Object you can use one of the next form:
Set<Integer> intSet = new HashSet<>();
Set<String> vSet = new HashSet<>();
Set mySet = new LinkedHashSet();
HashSet<String> myHashset = new HashSet<>();
Here is a simple example, where we create 2 Sets, HashSet and LinkedHashSet, and add into each for 5 elements. We can use the add() method for this.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

public class HashSetTest {
    public static void main(String[] args) {
        Set mySet = new HashSet();
        Set mySet2 = new LinkedHashSet();
//adding some string elements
        mySet.add("Stuart");
        mySet.add("Alex");
        mySet.add("Johnny");
        mySet.add("Igor");
        mySet.add("Bel");
        System.out.println(mySet);
        mySet2.add("Stuart");
        mySet2.add("Alex");
        mySet2.add("Johnny");
        mySet2.add("Igor");
        mySet2.add("Bel");
        System.out.println(mySet2);
    }
}
Here is the output of the program:
[Alex, Igor, Stuart, Johnny, Bel] [Stuart, Alex, Johnny, Igor, Bel]
As we mentioned above, HashSet does not maintain the order of elements, but LinkedHashSet does. It was LinkedHashSet that gave us the elements in the order we wrote them to the set.

Java Set Methods

Here are some of Java Set important methods:
  • boolean add(E e). Adds the specified element to the set if it is not already present (optional operation).

  • boolean remove(Object o). Removes the specified element from this set if it is present (optional operation).

  • boolean removeAll(Collection c). Removes from this set all of its elements that are contained in the specified collection (optional operation).

  • boolean retainAll(Collection c). Retains only the elements in this set that are contained in the specified collection (optional operation).

  • void clear(). Removes all the elements from the set.

  • Iterator iterator(). Returns an iterator over the elements in this set.

  • int size(). it is used to get the number of elements in the Set.

  • boolean isEmpty(). to check if Set is empty or not.

  • boolean contains(Object o). Returns true if this Set contains the specified element.

  • Iterator iterator(). Returns an iterator over the elements in this set. The elements are returned in no particular order.

  • Object[] toArray(). Returns an array containing all of the elements in this set. If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

The methods are similar to those of ArrayList, except that the add(Object o) method only adds an object to the set if it is not already there. The return value of the method is true if the object has been added, and false otherwise. There are also some methods inherited from Collection<> Interface: parallelStream(), removeIf(), stream() and forEach() method inherited from java.lang.Iterable Interface.

Java Set main operations example

In this example, we create an array of strings and then pass it to mySet using the Arrays.asList operation. Then we remove a couple more elements, and add a couple more. In this case, one of the elements in the set already exists: it will not be added. We will also try the operations of checking for emptiness isEmpty(), determining the size of the set size() and clearing the set of all elements clear().
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class HashSetTest2 {
   public static void main(String[] args) {
       //creating a string Array with some names
       String [] friends =  {"Stuart", "Ivy", "Johnny", "Alex", "Igor", "Tanya"};
       //creating a new set and adding elements from string array into it
       Set<String> mySet = new HashSet<>(Arrays.asList(friends));
       System.out.println(mySet);
       //removing two elements from the set
       mySet.remove("Igor");
       mySet.remove("Stuart");

       System.out.println(mySet);

       //adding 2 new Elements into set
       mySet.add("Dasha");
       mySet.add("Alex"); //it's second Alex, can't be added
       System.out.println(mySet);
       //cheking the size of mySet
       int size = mySet.size();
       System.out.println("The quantity of set's elements = " + size);
       //Checking if the set is empty
       System.out.println("Is mySet empty? " + mySet.isEmpty());
       //checking if some elements are in set
       System.out.println("Is Igor in set? " + mySet.contains("Igor"));
       System.out.println("Is Johnny in set? "+ mySet.contains("Johnny"));
       //deleting all elements from the set
       mySet.clear();
       System.out.println("Is mySet empty now? " + mySet.isEmpty());

   }
}
The output of the program is here:
[Alex, Igor, Stuart, Tanya, Johnny, Ivy] [Alex, Tanya, Johnny, Ivy] [Alex, Dasha, Tanya, Johnny, Ivy] The quantity of set's elements = 5 Is mySet empty? false Is Igor in set? false Is Johnny in set? true Is mySet empty now? true

Example with LinkedHashSet and set to Array

Let's write another program. In it, we will create a set based on the LinkedHashSet, add elements to it, and then convert the set to an array.
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
   public class LinkedHashSet3 {
       public static void main(String[] args) {
           Set<String> set = new LinkedHashSet<>();
           set.add("C");
           set.add("D");
           set.add("E");
           set.add("F");
           set.add("G");
           set.add("A");
           set.add("B");
           System.out.println(set);
           set.remove("F");// removing an element from our set
           set.remove("C sharp");//trying to remove element that isn't in set
           System.out.println(set.remove("C sharp"));
           System.out.println("Print our set with elements removed: ");
           System.out.println(set);

//set to array
           String strArray[] = set.toArray(new String[set.size()]);
           System.out.println("New Array from set: ");
           System.out.println(Arrays.toString(strArray));
           System.out.println(strArray[0]);

       }
   }
Here is the output of the program:
[C, D, E, F, G, A, B] false Print our set with elements removed: [C, D, E, G, A, B] New Array from set: [C, D, E, G, A, B] C

Set example with iterator

Let's create a set, then print it out using an iterator, and then remove all even numbers from it, also using an iterator.
import java.util.*;

public class SetTest5
{
   public static void main(String[] args)
   {

       Set<Integer> mySet = new HashSe<>();
       for(int i = 0; i < 10; i++)
           mySet.add(i);

       Iterator iterator = mySet.iterator();

       //simple iteration
       while(iterator.hasNext()){
           int i = (int) iterator.next();
       }
       System.out.println(" " + mySet);

       //modification of mySet using iterator - removing all even numbers
       iterator = mySet.iterator();
       while(iterator.hasNext()){
           int x = (int) iterator.next();
           if(x%2 == 0) iterator.remove();
       }
       System.out.println(mySet);

       }
}
The output of the program is here:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 3, 5, 7, 9

Example with TreeSet

If sorting is important to you, then use TreeSet implementation. In this short example, we will fill in the set with the names of friends, as in the previous examples. However, in a sorted TreeSet, the elements will immediately be written in sorted order. In this case, the names will be displayed alphabetically.
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {

   public static void main(String[] args) {

       Set mySet = new TreeSet<>();
       mySet.add("Stuart");
       mySet.add("Alex");
       mySet.add("Johnny");
       mySet.add("Igor");
       mySet.add("Bel");
       System.out.println(mySet);

   }
The output is:
[Alex, Bel, Igor, Johnny, Stuart]

Brief conclusions

  • The Java Set interface is part of the Java Collections Framework.

  • Implemented classes: AbstractSet, ConcurrentHashMap.KeySetView, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet.

  • The most popular Set implementations are HashSet, LinkedHashSet and TreeSet.

  • HashSet element order is determined by a complex algorithm. If storage order is important to you, use a TreeSet container, which stores objects sorted in ascending order in comparison order, or a LinkedHashSet, which stores elements in addition order.

  • Most often, sets are used to test membership. That is, to check whether an object belongs to a given set in the mathematical sense. So most often of all Set implementations in practice, HashSet is usually chosen. This implementation is optimized for fast searching.

  • You can’t add duplicate elements to a set, so you can use implementations of the Set interface to store unique elements.

  • Set allows you to add only one null element.

  • Set is not a list and does not support indexes or positions of its elements.

Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet