Skip to main content
Collections framework · Topic 3 of 8

Set types

Definition​

A Set holds no duplicates. HashSet has no defined order and is the fastest. LinkedHashSet keeps insertion order. TreeSet keeps items sorted. Pick by the order you need.

Example code​

Three sets, three orders

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

class Demo {
public static void main(String[] args) {
String[] fruits = {"pear", "apple", "fig", "apple", "banana"};

Set<String> hash = new HashSet<>(); // no order guarantee
Set<String> linked = new LinkedHashSet<>(); // insertion order
Set<String> sorted = new TreeSet<>(); // sorted order

for (String fruit : fruits) {
hash.add(fruit);
linked.add(fruit);
sorted.add(fruit);
}

System.out.println("linked: " + linked); // the duplicate "apple" was ignored
System.out.println("sorted: " + sorted);
System.out.println("size of hash: " + hash.size());
}
}

// Output:
// linked: [pear, apple, fig, banana]
// sorted: [apple, banana, fig, pear]
// size of hash: 4

Finished this page? Track your progress (saved only in your browser).