简体   繁体   中英

How to check if a Set contains an object which has one member variable equal to some value

I have a java Set of Result objects. My Result class definition looks like this:

private String url;
private String title;
private Set<String> keywords;

I have stored my information in a database table called Keywords which looks like this

Keywords = [id, url, title, keyword, date-time]

As you can see there isn't a one-to-one mapping between an object and a row in the database. I am using SQL (MySQL DB) to extract the values and have a suitable ResultSet object.

How do I check whether the Set already contains a Result with a given URL.

If the set already contains a Result object with the current URL I simply want to add the extra keyword to the Set of keywords, otherwise I create a new Result object for adding to the Set of Result objects.

When you iterate over the JDBC resultSet (to create your own set of Results) why don't you put them into a Map? To create the Map after the fact:

Map<String, List<Result>> map = new HashMap<String, List<Result>>();
for (Result r : resultSet) {
    if (map.containsKey(r.url)) {
        map.get(r.url).add(r);
    } else {
        List<Result> list = new ArrayList<Result>();
        list.add(r);
        map.put(r.url, list);
    }
}

Then just use map.containsKey(url) to check.

If it's possible, I suggest changing your database design to eliminate this problem. Your current design requries storing the id, url, title and date-time once per key word, which could waste quite a bit of space if you have lots of key words

I would suggest having two tables. Assuming that the id field is guarenteed to be unique, the first table would store the id, url, title and date-time and would only have one row per id. The second table would store the id and a key word. You would insert multiple rows into this table as required.

Is that possible / does that make sense?

You can use a Map with the URLs as the keys:

Map<String, Result> map = new HashMap<String, Result>();

for (Result r : results) {
    if (map.containsKey(r.url)) {
        map.get(r.url).keywords.addAll(r.keywords);
    } else {
        map.put(r.url, r);
    }
}

I think that you need to make an override on equals() method of your Result class. In that method you will put your logic that will check what you are looking for.

NB You also need to know that overrideng the equals() method, you need to override also hashCode() method.

For more on "overriding equals() and hashCode() methods" topic you can look at the this another question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM