1. Introduction
In Java, finding an element in a Set is often accomplished using the contains() method, which is a part of the Set interface. The contains() method checks if a specific element is present in the set and returns a boolean value accordingly. This guide demonstrates how to find an element in a Set in Java.
2. Program Steps
1. Initialize a Set with some integer elements.
2. Print the original Set to the console.
3. Use the contains() method to check if the Set contains a specific element.
4. Print the result of the search to the console.
3. Code Program
import java.util.Set;
import java.util.HashSet;
public class FindInSet {
public static void main(String[] args) {
// Step 1: Initialize a Set with some integer elements
Set<Integer> numbers = new HashSet<>(Set.of(1, 2, 3, 4, 5));
// Step 2: Print the original Set
System.out.println("Original Set: " + numbers);
// Step 3: Use the contains() method to check if the Set contains a specific element
boolean containsThree = numbers.contains(3);
// Step 4: Print the result of the search
System.out.println("Contains 3: " + containsThree);
}
}
Output:
Original Set: [1, 2, 3, 4, 5] Contains 3: true
4. Step By Step Explanation
Step 1: A Set named numbers is initialized with some integer elements.
Step 2: The original Set, numbers, is printed to the console.
Step 3: The contains() method of the Set interface is used to check if the Set numbers contains the integer 3. The result is stored in a boolean variable containsThree.
Step 4: The result of the search, stored in containsThree, is printed to the console, showing Contains 3: true as 3 is present in the original Set.