开发者

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

开发者 https://www.devze.com 2023-04-07 16:23 出处:网络
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 \"

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 e开发者_如何转开发ach 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?


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
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消