Java HashSet
A HashSet is a collection that holds each value at most once. Adding a value that is already present changes nothing.
A repeated add is ignored
Three adds run here, and Ada appears twice. The size prints 2, not 3.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>();
names.add("Ada");
names.add("Ben");
names.add("Ada");
System.out.println(names.size());
}
}Check which values are present
contains prints a verdict for each name. Cid was never added.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>();
names.add("Ada");
names.add("Ben");
System.out.println(names.contains("Ada"));
System.out.println(names.contains("Cid"));
}
}Remove a value from the set
remove deletes Ben from the set. The check then prints false and the size drops to 1.
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>();
names.add("Ada");
names.add("Ben");
names.remove("Ben");
System.out.println(names.contains("Ben"));
System.out.println(names.size());
}
}List values in sorted order
The values move into an ArrayList for sorting. The loop prints the sorted copy.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>();
names.add("Cid");
names.add("Ada");
names.add("Ben");
ArrayList<String> sorted = new ArrayList<String>(names);
Collections.sort(sorted);
for (String name : sorted) {
System.out.println(name);
}
}
}Example
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> tags = new HashSet<String>();
tags.add("java");
tags.add("code");
tags.add("java");
tags.add("data");
System.out.println(tags.size());
ArrayList<String> sorted = new ArrayList<String>(tags);
Collections.sort(sorted);
for (String tag : sorted) {
System.out.println(tag);
}
}
}Key points
- HashSet lives in java.util and is imported before use.
- add places a value into the set.
- A second add of the same value is ignored.
- contains reports whether a value is present.
- remove deletes a value from the set.
- size counts the distinct values in the set.
- A set promises no order for its values.
In this example, four adds run and the tag java appears twice. The set keeps java once, so the size prints 3. The sorted copy then lists the three distinct tags in alphabetical order.
Note
A sorted listing copies the values into an ArrayList and sorts that copy.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
A set receives the adds "Ada", "Ben", and "Ada". What does size print?