Using Set in Java

In Java, a set is part of the Java Collections Framework and is a collection that does not allow duplicate elements. The Set interface provides methods such as add(), remove(), and contains() for basic operations. It doesn't support index-based access, meaning you can't get an element based on its position in a set, like you can with a list. The three main classes implementing the Set interface are HashSet, LinkedHashSet, and TreeSet. The HashSet class provides constant-time performance for basic operations but does not guarantee any particular ordering of elements. LinkedHashSet, meanwhile, maintains the order in which elements are inserted. TreeSet ensures that elements are stored in sorted order based on their natural order or according to a provided comparator. When initializing a set, you can specify its type using generics. In this Java Set Example, we have created a set and filled it with data. Click Execute to run the Java Set Example online and see the result.
Using Set in Java Execute
import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<String> fruitSet = new HashSet<>();


        for (String fruit : fruitSet) {
Updated: Viewed: 51 times