Wouldn't Collections.disjoint(A, B) work? From the documentation:

Returns true if the two specified collections have no elements in common.

Thus, the method returns false if the collections contains any common elements.

Answer from Frontline on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ set-contains-method-in-java-with-examples
Set contains() method in Java with Examples - GeeksforGeeks
December 26, 2025 - Set.contains() method in Java is used to check if a specific element exists in a Set. It returns true if the element is present, otherwise false.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ set-in-java
Set in Java - GeeksforGeeks
After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(). ... import java.util.*; class Geeks { public static void main(String[] args) { Set<String> h = new HashSet<String>(); h.add("A"); h.add("B"); ...
Published: 2 weeks ago
Discussions

Something like 'contains any' for Java set? - Stack Overflow
I have two sets, A and B, of the same type. I have to find if A contains any element from the set B. What would be the best way to do that without iterating over the sets? The Set library has con... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How contains method of Set collection works - Stack Overflow
Hi I am new to java as i know Set collection doesn't take duplicate and its contains method should return true when element is already present in collection. I am trying to run below program but I am More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to check in java if Set contains object with some string value? - Stack Overflow
I have Set of objects. Each object has String value. I need to select all objects that have this value equal to "direction". Is it possible without iterating over the set? More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to check if a Java set contains multiple items at once?
I'd do it using lambda expressions: Set superSet = new HashSet<>(Arrays.asList("a", "b", "c", "d")); List smaller = Arrays.asList("c", "a"); if (smaller.stream().anyMatch(superSet::contains)) { System.out.println("yes"); } else { System.out.println("nope"); } if (Stream.of("e", "f").anyMatch(superSet::contains)) { System.out.println("yes"); } else { System.out.println("nope"); } More on reddit.com
๐ŸŒ r/learnjava
5
5
April 7, 2020
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ check if an element is present in a set in java
Check if an Element Is Present in a Set in Java | Baeldung
April 2, 2024 - That way, we can customize the ... fields. In short, the contains() method offers the most concise and straightforward way to check if an element is present in a given Set compared to the other methods....
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ java โ€บ util โ€บ hashset_contains.htm
Java HashSet contains() Method
Following is the declaration for java.util.HashSet.contains() method. ... The method call returns 'true' if this set contains the specified element.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ Set.html
Set (Java Platform SE 8 )
3 weeks ago - The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.
Top answer
1 of 5
10

From the Object javadoc

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

If the hashCode() method is not overridden then the Object's hashCode() method is used which is default implementation.

In your case you had overridden the equals method but you use the default implementation of the hashCode() as you didn't override the hashCode() method in your UserDefinedName class.

The UserDefinedName class overrides the equals method, and the hashCode contract demands that equal objects have equal hash codes. To fulfill this contract, you must override hashCode whenever you override equals

add following code and it will work.

public int hashCode() {
    return 37 * first.hashCode() + last.hashCode(); 
}
2 of 5
1

Because an hashSet uses the hashcode value of the object to store it. So it requires that you have to override the method hashCode in your own class. Since you didn't override it, it uses the hashCode method inherited from the object class.

The hashcode from the object class is calculated with the memory address of your object, i.e :

UserDefinedName p = new UserDefinedName("Carballo", "Videl");
System.out.println(p);
System.out.println(0x1e5e2c3);
System.out.println(p.hashCode());

Output :

UserDefinedName@1e5e2c3
31843011
31843011

So if you tried this, you will see that it outputs true :

Set<UserDefinedName> s = new HashSet<UserDefinedName>();
UserDefinedName p = new UserDefinedName("Carballo", "Videl");
s.add(p);
System.out.println(s.contains(p));

Now if you want to compare your User class correclty, you will have to override your hashCode method (you can generated it with eclipse) to generate the hashCode your object field by field.

If you have this method to your class, this will print true for the code you provide.

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((first == null) ? 0 : first.hashCode());
        result = prime * result + ((last == null) ? 0 : last.hashCode());
        return result;
    }
Find elsewhere
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java collections โ€บ hashset contains() method in java
HashSet contains() Method in Java
September 28, 2023 - HashSet.contains() is a boolean method to check if an item is present in an instance of HashSet or not. Simply put, whether the set contains the desired element. Java.util.HashSet provides an efficient implementation for it.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ hashset-contains-method-in-java
Java HashSet contains() Method - GeeksforGeeks
July 11, 2025 - The contains() method of the HashSet class in Java is used to check if a specific element is present in the HashSet or not. So, mainly it is used to check if a set contains any particular element.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 7 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ Set.html
Set (Java Platform SE 7 )
7 ... AbstractSet, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet ... A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
Top answer
1 of 6
31

In general, no. You need to iterate over the set and check each object to see if the property is equal to the value you are searching for. This is an O(n) operation.

There is one situation in which you could do it without iterating. If your object's equals method is defined in terms of equality of that String property, and if the hashCode method is also implemented correctly, then you can use the hashSet.contains to find an object with the correct value in O(1) time without requiring iterating over the set.

As I mentioned, this is a very specific use case and not a general solution. It might be useful if the string was some sort of unique identifier, but it won't work for your specific use case.

You might also want to consider other collections that would be better suited to your use case. You could for example if you are using Guava then you could consider using a Multimap.

Related

  • HashMap with multiple values under the same key
2 of 6
11

Yes this is possible by overriding the equals() method.

@Override 
public boolean  equals (Object object) {
     
}

You just want to check everything works in the equals method.

Code:

package com.webapp.test;

import java.util.ArrayList;
import java.util.List;

public class EmployeeModel {    

    public EmployeeModel(String name, String designation, long age) {
        this.name = name;
        this.designation = designation;
        this.age = age;
    }

    private String name;
    private String designation;
    private long age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public long getAge() {
        return age;
    }

    public void setAge(long age) {
        this.age = age;
    }

    @Override
    public boolean equals (Object object) {
        boolean result = false;
        if (object == null || object.getClass() != getClass()) {
            result = false;
        } else {
            EmployeeModel employee = (EmployeeModel) object;
            if (this.name == employee.getName() && this.designation == employee.getDesignation() && this.age.equals(employee.getAge())) {
                result = true;
            }
        }
        return result;
    }
}

public static void main(String args[]) {
    EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
    EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
    EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);

    List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
    employeeList.add(first);
    employeeList.add(second);
    employeeList.add(third);
    
    EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
    System.out.println("Check checkUserOne is in list or not ");
    System.out.println("Is checkUserOne Present = ? " + employeeList.contains(checkUserOne));
    
    EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
    System.out.println("Check checkUserTwo is in list or not");
    System.out.println("Is checkUserTwo Present = ? " + employeeList.contains(checkUserTwo));

}

Output:

Check checkUserOne is in list or not 
Is checkUserOne Present = ? true
Check checkUserTwo is in list or not 
Is checkUserTwo Present = ? false
๐ŸŒ
Java Guides
javaguides.net โ€บ 2023 โ€บ 09 โ€บ java-set-contains-example.html
Java Set contains() example
September 26, 2023 - The contains() method of the Java Set interface returns true if the set contains the specified element.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ set-containsall-method-in-java-with-examples
Set containsAll() Method in Java - GeeksforGeeks
July 11, 2025 - The containsAll() method of Set in Java is used to check if a collection contains all the elements of a specified collection.
๐ŸŒ
Jenkov
jenkov.com โ€บ tutorials โ€บ java-collections โ€บ set.html
Java Set
October 13, 2020 - To determine if the Set contains the element, the Set will internally iterate its elements and compare each element to the object passed as parameter. The comparison uses the Java equals method of the element to check if the element is equal ...
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-hashsetcontains-function-in-java
What is the HashSet.contains() function in Java?
The contains() method of HashSet checks if the specified element is present in the HashSet or not.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-check-if-a-set-contains-a-specific-element-in-java-559973
How to Check If a Set Contains a Specific Element in Java | LabEx
The contains() method takes one argument, the element you want to check for, and returns a boolean value: true if the element is found in the collection, and false otherwise. Let's create a simple Java program to demonstrate how to use the ...
๐ŸŒ
Oracle
docs.oracle.com โ€บ en โ€บ java โ€บ javase โ€บ 11 โ€บ docs โ€บ api โ€บ java.base โ€บ java โ€บ util โ€บ Set.html
Set (Java SE 11 & JDK 11 )
January 20, 2026 - Package java.util ยท Type Parameters: ... JobStateReasons, LinkedHashSet, TreeSet ยท public interface Set<E> extends Collection<E> A collection that contains no duplicate elements....
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ mastering-complex-data-structures-in-java โ€บ lessons โ€บ understanding-sets-in-java
Understanding Sets in Java
Welcome to our Java Sets lesson! In Java, sets are represented by the HashSet<E> collection, which can only hold unique elements.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-set
Java Set โ€“ Set in Java | DigitalOcean
Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.