Advertisement

Google Ad Slot: content-top

Java Collection Set


A Set in Java is a collection of unique elements that does not allow duplicates. It is part of the Java Collections Framework and is useful when uniqueness is required, such as storing IDs, unique names, or distinct elements.

Set Type

Description

Implementation

HashSet

Stores unique elements with no order

HashSet<E>

LinkedHashSet

Maintains insertion order

LinkedHashSet<E>

TreeSet

Maintains elements in sorted order

TreeSet<E>


Using HashSet:

import java.util.HashSet;
import java.util.Set;

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

set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate, ignored

System.out.println(set); // Output: [Banana, Apple, Cherry] (unordered)
}
}

Try it yourself

Using LinkedHashSet:

import java.util.LinkedHashSet;
import java.util.Set;

public class Main {
public static void main(String[] args) {
Set<String> set = new LinkedHashSet<>();

set.add("Apple");
set.add("Banana");
set.add("Cherry");

System.out.println(set); // Output: [Apple, Banana, Cherry] (insertion order)
}
}
Try it yourself

Using TreeSet:

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

public class Main {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();

set.add(30);
set.add(10);
set.add(20);

System.out.println(set); // Output: [10, 20, 30] (sorted order)
}
}
Try it yourself

Set Methods:

Method

Description

add(E e)

Adds an element (ignores duplicates)

remove(E e)

Removes an element

contains(E e)

Checks if an element exists

size()

Returns the number of elements

isEmpty()

Checks if the set is empty

clear()

Removes all elements

iterator()

Returns an iterator to traverse the set