How to check in java if Set contains object with some string value?

I know this is an old question, but...

Short answer: NO, it's not possible...

Using equals() or contains() as recommended by other fellows should be restricted to situations where the attributes you are using for filtering are actually a part of the objects Identity. I don't see any way but a O(n) algorithm.

If you are considering native functions, Java 8 brought the Stream API and concepts of Functional Programming, allowing easier and cleaner loop calls. Nonetheless it is worth noting that for your situation all objects in your collection will have to be checked, so complexity will remain O(n).

Example with Java 8's stream().filter()

public static void main(String[] args...){
    Set<MyClass> mySet = new HashSet<>();
    mySet.add(new MyClass("Obj 1", "Rio de Janeiro"));
    mySet.add(new MyClass("Obj 2", "London"));
    mySet.add(new MyClass("Obj 3", "New York"));
    mySet.add(new MyClass("Obj 4", "Rio de Janeiro"));

    Set<MyClass> filtered = mySet.stream()
                                 .filter(mc -> mc.getCity().equals('Rio de Janeiro'))
                                 .collect(Collectors.toSet());

    filtered.forEach(mc -> System.out.println("Object: "+mc.getName()));

    // Result:
    //    Object: Obj 1 
    //    Object: Obj 4 
}

Yes this is possible by overwriting 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

You could also use Predicate like in this question to filter the list : What is the best way to filter a Java Collection?


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