Mark As Completed Discussion

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}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment