Search code examples
javafiltertreeset

Get a Boolean value for whether an Object partially matches (Java)


I think this is an easy question, if I could figure out search terms to describe it. It's similar to Finding all objects that have a given property inside a collection except I just want a Boolean "is it there" result.

Say I have a sorted TreeSet of Cats, each of which has a name, age, food, etc. I have something complicated to do for each potential cat name, but I want to skip it if there already a cat in my TreeSet with that name. I don't care if any of the other attributes match. I obviously can't do if (!AlltheCats.contains(candidateName))... because then I'll have a type mismatch between the string candidateName and the object Cat. But I don't think I can create an object to search for an identical match to, because I don't care about the values for age, food, etc.

What would be an efficient/elegant way to do this?


Solution

  • Create a HashSet of Strings containing names, every time you invoke your method on a cat, check first if it is already in the set, and if it is, skip this cat. Modify this set as you keep going.

    (*)This answer assumes you want to invoke the method for one cat [and not 0] with identical name.

    Should look something like that:

        Set<String> names = new HashSet<String>();
        for (Cat c : set) { 
            if (names.contains(c.getName())) {
                continue;
            }
            names.add(c.getName());
            c.foo(); //your method here
        }