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
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;
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With