Java 8 Stream API toMap 转换为 TreeMap

2022-01-22 00:00:00 lambda java-8 java java-stream collectors
public class Message {
    private int id;
    private User sender;
    private User receiver;
    private String text;   
    private Date senddate;
..
}

我有

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

我需要将它们转换为

TreeMap<User,List<Message>> map

我知道如何使用 HashMap 进行转换

I know how to do transform to HashMap using

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

但我需要 TreeMap :密钥 - 最新消息发送日期优先的用户值 - 按发送日期最新排序的列表

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

用户类的一部分

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

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

}

用户比较器:

     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());
        }
    }

推荐答案

可以使用重载的groupingBy 方法并将 TreeMap 作为 供应商:

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()));

相关文章