Say I have the following map:
Map<Member, List<Message>> messages = ... //constructed somehow
I would like to use the java 8 stream api in order to obtain a:
SortedMap<Message, Member> latestMessages = ...
Where the comparator passed into the SortedMap/TreeMap would be based on the message sendDate field.
Furthermore, of the list of sent messages, I would select the latest message which would become the key to the sorted map.
How can I achieve that?
edit 1:
Comparator<Message> bySendDate = Comparator.comparing(Message::getSendDate);
SortedMap<Message, Member> latestMessages = third.entrySet().stream()
.collect(Collectors.toMap(e -> e.getValue().stream().max(bySendDate).get(), Map.Entry::getKey, (x, y) -> {
throw new AssertionError();
}, () -> new TreeMap(bySendDate.thenComparing(Comparator.comparing(Message::getId)))));
I get the following compilation error:
The method collect(Collector<? super T,A,R>) in the type Stream<T> is not applicable for the arguments (Collector<Map.Entry<Member,List<Message>>,?,TreeMap>)
Messagewith a specificsendDate, even if different message with the same date but different sender and receiver exist.