Check If a Element Exists in Java LinkedHashSet Example

LinkedHashSet Examples


This Java example shows how to check whether an element is contained in Java LinkedHashSet using contains() method.

Check If an Element Exists in Java LinkedHashSet Example

In the following example, we are checking whether LinkedHashSet contains a "Paris" city object or not.
package com.javaguides.collections.linkedhashsetexamples;

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetSimpleOperationsExample {
    public static void main(String[] args) {
        Set < String > popularCities = new LinkedHashSet < > ();

        popularCities.add("London");
        popularCities.add("New York");
        popularCities.add("Paris");
        popularCities.add("Dubai");

        // Check if the HashSet contains an element
        String cityName = "Paris";
        if (popularCities.contains(cityName)) {
            System.out.println(cityName + " is in the popular cities set.");
        } else {
            System.out.println(cityName + " is not in the popular cities set.");
        }
    }
}

Output

Paris is in the popular cities set.



Comments