Set
The Set
interface in Java represents a collection of unique elements. It does not allow duplicate elements in the collection. The Set
interface is a part of the Java Collections Framework and provides several useful methods for working with sets.
To use the Set
interface, you need to import the java.util.Set
package.
Here's an example that demonstrates the usage of the Set
interface:
TEXT/X-JAVA
1import java.util.HashSet;
2import java.util.Set;
3
4public class Main {
5
6 public static void main(String[] args) {
7 // Create a set
8 Set<String> set = new HashSet<>();
9
10 // Adding elements to the set
11 set.add("Apple");
12 set.add("Banana");
13 set.add("Orange");
14 set.add("Apple");
15
16 // Printing the set
17 System.out.println("Set: " + set);
18
19 // Checking if an element exists in the set
20 boolean contains = set.contains("Banana");
21 System.out.println("Contains 'Banana' in set: " + contains);
22
23 // Removing an element from the set
24 boolean removed = set.remove("Orange");
25 System.out.println("Removed 'Orange' from set: " + removed);
26
27 // Printing the updated set
28 System.out.println("Updated Set: " + set);
29
30 // Checking the size of the set
31 int size = set.size();
32 System.out.println("Size of the set: " + size);
33 }
34
35}
xxxxxxxxxx
35
}
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// Create a set
Set<String> set = new HashSet<>();
// Adding elements to the set
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Apple");
// Printing the set
System.out.println("Set: " + set);
// Checking if an element exists in the set
boolean contains = set.contains("Banana");
System.out.println("Contains 'Banana' in set: " + contains);
// Removing an element from the set
boolean removed = set.remove("Orange");
System.out.println("Removed 'Orange' from set: " + removed);
// Printing the updated set
System.out.println("Updated Set: " + set);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment