Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two sets conditionally

Tags:

java

java-8

I have a Person object which has a name attribute and some other attributes. I have two HashSet with Person objects. Note that name is not an unique attribute meaning that two Persons with same name can have different height so using HashSet does not guarantee that two Persons with same name are not in the same set.

I need to add one set to another so there are no Persons in the result with the same name. So something like this:

public void combine(HashSet<Person> set1, HashSet<Person> set2){
    for (String item2 : set2) {
        boolean exists = false;
        for (String item1 : set1) {
            if(item2.name.equals(item1.name)){
                exists = true;
            }
        }
        if(!exists){
            set1.add(item2);
        }
    }
}

Is there a cleaner way of doing this in java8?

like image 861
user1985273 Avatar asked Feb 04 '26 16:02

user1985273


1 Answers

set1.addAll(set2.stream().filter(e -> set1.stream()
                    .noneMatch(p -> p.getName().equals(e.getName())))
                    .collect(Collectors.toSet()));
like image 121
Ousmane D. Avatar answered Feb 09 '26 09:02

Ousmane D.