I have an Employee class:
public class Employee {
public enum Sex {
MALE, FEMALE
}
private final String name;
private final Sex gender;
private final LocalDate dateOfBirth;
private final double salary;
private final List<String> roles;
// Constructor
public Employee(String name, Sex gender, LocalDate dateOfBirth, double salary, List<String> roles) {
this.name = name;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.salary = salary;
this.roles = roles;
}
// Getters & toString omitted
public static List<Employee> listOfStaff() {
List<Employee> staff = new ArrayList<>();
staff.add(new Employee("Jack", Employee.Sex.MALE,
IsoChronology.INSTANCE.date(1954, 12, 2), 49999.00,
new ArrayList<>(Arrays.asList("Manager", "Director"))));
staff.add(new Employee("Jill", Employee.Sex.FEMALE,
IsoChronology.INSTANCE.date(1995, 10, 25), 24999.00,
new ArrayList<>(Arrays.asList("Secretary", "Manager", "Personnel"))));
staff.add(new Employee("Dorothy", Employee.Sex.FEMALE,
IsoChronology.INSTANCE.date(1972, 4, 7), 21999.00,
new ArrayList<>(Arrays.asList("Secretary", "Receptionist"))));
staff.add(new Employee("Bert", Employee.Sex.MALE,
IsoChronology.INSTANCE.date(1968, 11, 5), 21999.00,
new ArrayList<>(Arrays.asList("Clerk", "Receptionist"))));
staff.add(new Employee("Mary", Employee.Sex.FEMALE,
IsoChronology.INSTANCE.date(2001, 12, 3), 16999.00,
new ArrayList<>(Arrays.asList("Trainee", "Receptionist"))));
staff.add(new Employee("Matthew", Employee.Sex.MALE,
IsoChronology.INSTANCE.date(1962, 4, 7), 12999.00,
new ArrayList<>(Arrays.asList("Personnel", "Receptionist"))));
return staff;
}
}
I can extract a role and people within that role iteratively:
public class TestGrouping {
/* Grouping streams */
public static void main(String[] args) {
Map<String, List<String>> roleAndNames = new HashMap<>();
for (Employee e : Employee.listOfStaff()) {
List<String> roles = e.getRoles();
List<String> names = new ArrayList<>();
names.add(e.getName());
for (String r : roles) {
if(roleAndNames.get(r) == null) {
roleAndNames.put(r, names);
} else {
roleAndNames.get(r).add(e.getName());
}
}
}
for (Map.Entry<String, List<String>> entry : roleAndNames.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}
}
}
Which gives me the following output:
I have tried doing the same thing declaratively using streams but can't seem to get the same results.
Thought I might be able to do this using groupingBy() and collectingAndThen() but no joy!
Is this possible?
