Reputation: 417
How Do I collect in java 8 to a set by some field? for example: I have 2 object with different hashes (that's why they are two entities in the set) but I want to have a set with only one instance of it
tried this: but it gives me two students while I have only 1 unique.
Set<Man> students =
people.stream().collect( Collectors.mapping( Man::isStudent, Collectors.toSet()));
name:"abc" , id:5 (hash 1XX)
name:"abc", id:5 (has 5XX)
and I want the set to contain only one instance
Thanks
Upvotes: 3
Views: 2119
Reputation: 11620
Best solution would be to overwrite hashCode
and equals
methods in your Man class. Because Set is a type of collection that would require those methods, when adding/removing any element.
If you are interested only in collection of unique elements (read only), you can reduce your collection to map, where key would be name
proparety and then take the values.
Collection<Man> uniqueByName= myCollection.stream().collect(
Map::getName,
Function.identity()
).values();
Upvotes: 1
Reputation: 15852
You have to override the hashCode
and equals
. The possible implementation is:
@Override
public int hashCode() {
return this.name.hashCode * 31 + id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student s = (Student) o;
if (!getName().equals(s.getName())) return false;
if (getId() != appError.getStatus()) return false;
return true;
}
Upvotes: 1