Java 8 Stream API toMap 转换为 TreeMap

Java 8 Stream API toMap converting to TreeMap(Java 8 Stream API toMap 转换为 TreeMap)

本文介绍了Java 8 Stream API toMap 转换为 TreeMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于Java 8 Stream API toMap 转换为 TreeMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java 8 Stream API toMap 转换为 TreeMap

基础教程推荐