Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the spectra-pro domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home4/mahidhar/public_html/wp-includes/functions.php on line 6114
Set - Java | tutorialQ

Set – Java

Overview:
A Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction, providing a way to store unique elements. Sets are used when you want to maintain a collection of distinct items and have no need for indexing or ordering.

Supported Operations:

  • Adding elements: add(E e) – adds the specified element to the set if it is not already present.
  • Removing elements: remove(Object o) – removes the specified element from the set if it is present.
  • Checking for existence: contains(Object o) – returns true if the set contains the specified element.
  • Size of the set: size() – returns the number of elements in the set.
  • Iterating over elements: iterator() – returns an iterator over the elements in the set.

HashSet

HashSet is a widely used implementation of the Set interface. It uses a hash table for storage, providing constant-time performance for basic operations like add, remove, and contains.

Java
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
    public static void main(String[] args) {
        // Example using basketball team names
        Set<String> basketballTeams = new HashSet<>();
        // Adding elements
        basketballTeams.add("Lakers");
        basketballTeams.add("Warriors");
        basketballTeams.add("Bulls");
        basketballTeams.add("Lakers"); // Duplicate, will not be added       
        // Checking for existence
        System.out.println("Contains Warriors? " + basketballTeams.contains("Warriors")); // Output: true        
        // Removing elements
        basketballTeams.remove("Bulls");        
        // Size of the set
        System.out.println("Number of teams: " + basketballTeams.size()); // Output: 2        
        // Iterating over elements
        for (String team : basketballTeams) {
            System.out.println("Team: " + team);
        }
    }
}

LinkedHashSet

LinkedHashSet is an ordered version of HashSet that maintains a doubly linked list running through all its entries. It provides predictable iteration order (insertion-order).

Java
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
    public static void main(String[] args) {
        // Example using golf player names
        Set<String> golfPlayers = new LinkedHashSet<>();
       // Adding elements
        golfPlayers.add("Tiger Woods");
        golfPlayers.add("Phil Mickelson");
        golfPlayers.add("Rory McIlroy");
        golfPlayers.add("Tiger Woods"); // Duplicate, will not be added        
        // Checking for existence
        System.out.println("Contains Mickelson? " + golfPlayers.contains("Phil Mickelson")); 
        // Output: true        
        // Removing elements
        golfPlayers.remove("Rory McIlroy");        
        // Size of the set
        System.out.println("Number of players: " + golfPlayers.size()); // Output: 2        
        // Iterating over elements
        for (String player : golfPlayers) {
            System.out.println("Player: " + player);
        }
    }
}

TreeSet

TreeSet is an implementation of the Set interface that uses a tree for storage. It is sorted according to the natural ordering of its elements or by a comparator provided at set creation time.

Java
import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        // Example using baseball team names
        Set<String> baseballTeams = new TreeSet<>();        
        // Adding elements
        baseballTeams.add("Yankees");
        baseballTeams.add("Red Sox");
        baseballTeams.add("Dodgers");
        baseballTeams.add("Yankees"); // Duplicate, will not be added        
        // Checking for existence
        System.out.println("Contains Red Sox? " + baseballTeams.contains("Red Sox")); // Output: true        
        // Removing elements
        baseballTeams.remove("Dodgers");        
        // Size of the set
        System.out.println("Number of teams: " + baseballTeams.size()); // Output: 2        
        // Iterating over elements
        for (String team : baseballTeams) {
            System.out.println("Team: " + team);
        }
    }
}

EnumSet

EnumSet is a specialized Set implementation for use with enum types. All the elements in an enum set must come from a single enum type that is specified when the set is created.

Java
import java.util.EnumSet;
import java.util.Set;

public class EnumSetExample {
    enum HockeyPlayers {
        WAYNE_GRETZKY, SIDNEY_CROSBY, ALEX_OVECHKIN
    }

    public static void main(String[] args) {
        // Creating an EnumSet
        Set<HockeyPlayers> players = EnumSet.of(HockeyPlayers.WAYNE_GRETZKY, HockeyPlayers.SIDNEY_CROSBY);        
        // Adding elements
        players.add(HockeyPlayers.ALEX_OVECHKIN);        
        // Checking for existence
        System.out.println("ContainsOvechkin? " + players.contains(HockeyPlayers.ALEX_OVECHKIN)); // Output: true        
        // Removing elements
        players.remove(HockeyPlayers.SIDNEY_CROSBY);        
        // Size of the set
        System.out.println("Number of players: " + players.size()); // Output: 2        
        // Iterating over elements
        for (HockeyPlayers player : players) {
            System.out.println("Player: " + player);
        }
    }
}

Conclusion

The Set interface in Java provides a way to store unique elements, with various implementations catering to different requirements:

  • HashSet for general-purpose use with fast operations.
  • LinkedHashSet for maintaining insertion order.
  • TreeSet for sorted order.
  • EnumSet for enum-specific sets.

By understanding the characteristics and appropriate use cases for each implementation, you can effectively manage collections of unique elements in your Java applications.

Scroll to Top