-4

I'd like group by a field a select

Guess this class:

public class Person {
   private Name name;
   private Address address;
   ...
}

public class Name {
   private String name;
   private String fatherName;
   private String motherName;
}

I'd like to group by Person.getName().getMotherName() and select Person.getName() as grouping object key.

Collection<Person> persons = new ...

Map<Name, List<Person>> group = persons.stream()
  .collect(groupingby(p -> p.getName().getMotherName());

As you can see, I'd like to get a Map<Name, List<Person>>, instead of a Map<String, List<Person>>

Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 5
    How would this work? What happens if you have two `Person`s with the same `name` but different `fatherName`? Which `fatherName` would you assign to the `Name` object used as the key for the group containing both? – MTCoster Feb 19 '19 at 15:09
  • Please elaborate *group by `Person.getName().getMotherName()` and select `Person.getName()` as grouping object key.* .. Would two `Name`s be equal if their `motherName`s are equal? – Naman Feb 19 '19 at 15:11

2 Answers2

1

As you can't override equals() I can think of this way:

Create a wrapper around Name which overrides equals() and hashCode() for Name.getMotherName():

public class NameWrapper {
    private final Name name;
    public NameWrapper(Name name) {
        this.name = name;
    }

    @Override
    public int hashcode() {
        return name.getMotherName().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(obj == this) return true;
        if(!(obj instanceof NameWrapper)) return false;
        NameWrapper other = (NameWrapper) obj;
        return name.getMotherName().equals(other.name.getMotherName());
    }
}

Then you can map the Person#getName() to a NameWrapper and group by that:

Map<NameWrapper, List<Person>> group = persons.stream()
    .collect(Collectors.groupingBy(p -> new NameWrapper(p.getName())));
Lino
  • 19,604
  • 6
  • 47
  • 65
0

You can use :

Map<Name, List<Person>> group = persons.stream()
        .collect(Collectors.groupingBy(p -> p.getName()));

And you have to Overide the hashCode and equald in your Name class.

@Override
public boolean equals(Object o) {
    // your equals code
}

@Override
public int hashCode() {
    // your hash code
}
guest
  • 128
  • 3