6

Is it possible to transform List<Entry> to Map<Employee, Map<LocalDate, Entry>> with one lambda expression?

public class Entry {
    Employee employee;
    LocalDate date;
}

So far i have came up with something like this:

entries.stream().collect(Collectors.toMap(Collectors.groupingBy(Entry::getEmployee), Collectors.groupingBy(Entry::getDate), Function.identity()));

But this gives a compilation error:

no suitable method found for 
toMap(java.util.stream.Collector<com.a.Entry,capture#1 of ?,java.util.Map<com.a.Employee,
java.util.List<com.a.Entry>>>‌​,java.util.stream.Co‌​llector<com.a.Entry,‌​capture#2 of ?, 
java.util.Map<java.time.LocalDate,java.util.List<com.a.Ent‌ry>>>,
java.util.func‌​tion.Function<java.l‌​ang.Object,java.lang‌​.Object>) 

Thanks

2
  • Are you sure that Employee is a suitable key for a map? BTW, define "does not work". Commented Jan 17, 2017 at 23:01
  • compilation error: no suitable method found for toMap(java.util.stream.Collector<com.a.Entry,capture#1 of ?,java.util.Map<com.a.Employee,java.util.List<com.a.Entry>>>,java.util.stream.Collector<com.a.Entry,capture#2 of ?,java.util.Map<java.time.LocalDate,java.util.List<com.a.Entry>>>,java.util.function.Function<java.lang.Object,java.lang.Object>) Commented Jan 17, 2017 at 23:07

1 Answer 1

13

Assuming Entry has getters and Employee overrides hashCode() and equals():

Map<Employee, Map<LocalDate, Entry>> result = entries.stream()
        .collect(Collectors.groupingBy(Entry::getEmployee,
                Collectors.toMap(Entry::getDate, Function.identity())));

Note that this will throw an exception if an employee has duplicate dates.

Sign up to request clarification or add additional context in comments.

4 Comments

wicket, works perfectly. Exception on duplicates is expected behavior. Thank you
And what if i'd need Map<String, Map<LocaleDate,Entry>> where key for the map is Employee::getUsername ? Is it possible to manipulate the keys as well?
@przem Sure, just replace Entry::getEmployee with entry -> entry.getEmployee().getUsername().
noooooo i cant be that simple!!! :-D many many thanks! works like a dream

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.