Java 8 Stream API toMap converting to TreeMap

VoldemarP picture VoldemarP · Jan 31, 2016 · Viewed 22.1k times · Source
public class Message {
    private int id;
    private User sender;
    private User receiver;
    private String text;   
    private Date senddate;
..
}

I have

List<Message> list= new ArrayList<>();

I need to transform them to

TreeMap<User,List<Message>> map

I know how to do transform to HashMap using

list.stream().collect(Collectors.groupingBy(Message::getSender));

But I need TreeMap with: Key - User with newest message senddate first Value - List sorted by senddate newest first

Part of User class

    public class User{
    ...
    private List<Message> sendMessages;
    ...

   public List<Message> getSendMessages() {
        return sendMessages;
    }

}

User comparator:

     public class Usercomparator implements Comparator<User> {
        @Override
        public int compare(User o1, User o2) {
            return o2.getSendMessages().stream()
.map(message -> message.getSenddate())
.max(Date::compareTo).get()
           .compareTo(o1.getSendMessages().stream()
.map(message1 -> message1.getSenddate())
.max(Date::compareTo).get());
        }
    }

Answer

Mrinal picture Mrinal · Jan 31, 2016

You can use overloaded groupingBy method and pass TreeMap as Supplier:

TreeMap<User, List<Message>> map = list
            .stream()
            .collect(Collectors.groupingBy(Message::getSender,
                    () -> new TreeMap<>(new Usercomparator()), toList()));