Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 collect to set according to some field

Tags:

java

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

like image 724
Bazuka Avatar asked Jan 21 '26 05:01

Bazuka


2 Answers

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;
}
like image 65
xenteros Avatar answered Jan 23 '26 21:01

xenteros


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();
like image 40
Beri Avatar answered Jan 23 '26 19:01

Beri



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!