Convert map to another map using java 8 stream API

Let's say I have the following map:

Map<Member, List<Message>> messages = ... //constructed somehow

I would like to use java 8 api thread to get:

SortedMap<Message, Member> latestMessages = ...

If the comparator passed in SortedMap / TreeMap will be based on the messageDate field of the message.

In addition, from the list of sent messages, I would choose the last message, which will become the key to the sorted map.

How can i achieve this?

change 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>)
+4
source share
1 answer

Allows you to dissolve this in two parts.

Map<Member, List<Message>> messages Map<Message, Member> latestMessages, (Member) :

Map<Message, Member> latestMessages0 = messages.entrySet().stream()
    .collect(Collectors.toMap(
        e -> e.getValue().stream().max(Comparator.comparing(Message::getSendDate)).get(),
        Map.Entry::getKey));

map , , .


-, , sendDate, , Messages, . , Long, :

Comparator<Message> bySendDate=Comparator.comparing(Message::getSendDate);
SortedMap<Message, Member> latestMessages = messages.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)))));

, , , .

+9

All Articles