user1746708
user1746708

Reputation: 691

how can I implement the union and intersection of set theory with sets of objects

hi i've seen this post how to implement the union and intersection when it you have two sets of data,that are strings.how can i do the same when my sets contain objects,and i want to get the union of only one property of each object?

Upvotes: 2

Views: 3192

Answers (4)

dgmora
dgmora

Reputation: 1269

Intersection is using contains, which uses equals. You should implement equals() method on the class that you want to do intersection.

I didn't find specific comments about set.addAll() implementation, but most probably it also uses equals() to determine if an object is already on the set.

If you want to compare only by a field, your equals() should only compare this field.

Upvotes: 0

tadaskay
tadaskay

Reputation: 111

As in this answer, use Collection methods retainAll(Collection)- intersection and #addAll(Collection)- union.

Since those methods use equals, you also have to override equals method in your Class and implement one-property based comparison.

In case it's simple comparison, here's an example (generated by my IDEA):

public class Main {

private Integer age;

...

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Main main = (Main) o;

    if (age != null ? !age.equals(main.age) : main.age != null) return false;

    return true;
}

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

But I want to override them somehow so that it wont add an object if there's an object already in my set that has the same value in a selected property.If i'm not clear enough tell me so i can write an example.

I think the best way to do this is to use a ConcurrentMap.

ConcurrentMap<String, MyType> map = new ConcurrentHashMap<>();

// the collection to retain.
for(MyType mt: retainedSet) map.put(mt.getKey(), mt);

// the collection to keep if not duplicated
for(MyType mt: onlyIfNewSet) map.putIfAbsent(mt.getKey(), mt);

// to get the intersection.
Set<String> toKeep = new HashSet<>();
for(MyType mt: onlyIfNewSet) toKeep.add(mt.getKey());

// keep only the keys which match.
map.keySet().retainAll(toKeep);

Upvotes: 2

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

Google Guava, has Sets class which contains these methods and many more.

Upvotes: 1

Related Questions