Sets
The Set
interface provides a way to store unique elements. This tutorial will teach you how to use sets in Java.
Creating a Set
To create a set, use the HashSet
class:
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names);
}
}
Checking for Elements in a Set
Use the contains
method to check if an element exists in a set:
public class Main {
public static void main(String[] args) {
Set names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.contains("Bob")); // Outputs: true
}
}
Removing Elements from a Set
Use the remove
method to remove elements from a set:
public class Main {
public static void main(String[] args) {
Set names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.remove("Bob");
System.out.println(names); // Outputs: [Alice, Charlie]
}
}
Iterating Over a Set
You can iterate over a set using a for-each loop:
public class Main {
public static void main(String[] args) {
Set names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
System.out.println(name);
}
}
}
Continue exploring our intermediate tutorials to learn more about Java programming.