Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from two hash set

Tags:

java

set

hashset

In my case i have two hash sets one set contain friend's name and number and another set contain existing friend's name and number this data retrieved from db and stored into set how to compare and removing duplicates from tow set and intersection data stored into new set?
i need code for that in google i saw the comparator in comparator they used only one set but in my case i am checking two sets sorry for my bad english

like image 938
Karthik Keyan Avatar asked Jun 05 '26 11:06

Karthik Keyan


1 Answers

Assuming we have set1 and set2 we can do the following

    Set set3 = new HashSet(set1);
    set3.retainAll(set2);    
    set1.removeAll(set3);
    set2.removeAll(set3);

in your case this is

public class Friend {
    String name;
    String number;

    public Friend(String name, String number) {
        this.name = name;
        this.number = number;
    }

    @Override
    public int hashCode() {
        return name.hashCode() + 31 * number.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Friend)) {
            return false;
        }
        Friend other = (Friend)obj;
        return other.number.equals(number) && other.name.equals(name);
    }

    @Override
    public String toString() {
        return name + "-" + number;
    }
}

public static void main(String[] args) throws Exception {
    Set<Friend> set1 = new HashSet<Friend>();
    set1.add(new Friend("Karthik", "111"));
    set1.add(new Friend("Mani", "222"));
    set1.add(new Friend("Karthik", "111"));
    set1.add(new Friend("Mani", "444"));
    set1.add(new Friend("Karthik", "111"));

    Set<Friend> set2 = new HashSet<Friend>();
    set2.add(new Friend("Karthik", "111"));
    set2.add(new Friend("Raju", "3333"));

    Set<Friend> set3 = new HashSet<Friend>(set1);
    set3.retainAll(set2);
    set1.removeAll(set3);
    set2.removeAll(set3);

    System.out.println(set1);
    System.out.println(set2);
}

output

[Mani-444, Mani-222]
[Raju-3333]
like image 174
Evgeniy Dorofeev Avatar answered Jun 07 '26 01:06

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!