Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27255

Copying a collection of objects to another collection without duplicates using aggregate operations

I have a List of items named items and am copying this list to a Set using:

 List<Item> items = new ArrayList<>();

    items.add(new Item("Suremen Body Spray", 1900, 45));
    items.add(new Item("HP wireless mouse", 5500, 5));
    items.add(new Item("UWS USB memory stick", 1900, 8));
    items.add(new Item("MTN modem", 1900, 45));
    items.add(new Item("MTN modem", 1900, 45));

    Collection<Item> noDups = new LinkedHashSet<Item>(items); //Copy items to noDups

    //Print the new collection
    noDups.stream()
       .forEach(System.out::println);

When I run the code, all the items are copied into the collection as shown in the output.

enter image description here

A different test using just Strings works just fine:

List<String> names = new ArrayList<>();

    names.add("Eugene Ciurana");
    names.add("Solid Snake");
    names.add("Optimus Prime");
    names.add("Cristiano Ronaldo");
    names.add("Cristiano Ronaldo");


    Collection<String> itemCollection = new HashSet<String>(names);
     itemCollection.stream()
           .forEach(System.out::println);

enter image description here

What method can I use to copy the list into the set without the duplicate? Are there any aggregate operations for this, or do I have to write a custom method?

Upvotes: 1

Views: 149

Answers (2)

Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27255

Just thought I add an answer to show how I finally did it (Using Adam's suggestion of course)

I added the implementations of the equals and hashCode methods to my Item class:

@Override
public boolean equals(Object obj) {
    if(!(obj instanceof Item)) {
        return false;
    }
    if(obj == this) {
        return true;
    }

    Item other = (Item)obj;
    if(this.getName().equals(other.getName())
           && this.getPrice() == other.getPrice() 
           && this.getCountryOfProduction().equals(other.countryOfProduction)) {
        return true;
    } else {
        return false;
    }

}

public int hashCode() {
    int hash = 3;

    hash = 7 * hash + this.getName().hashCode();
    hash = 7 * hash + this.getCountryOfProduction().hashCode();
    hash = 7 * hash + Double.valueOf(this.getPrice()).hashCode();
    return hash;

}

Upvotes: 1

Adam Siemion
Adam Siemion

Reputation: 16039

You need to implement the equals and the hashCode method in your Item class.

Upvotes: 5

Related Questions