Java 8 Stream API toMap 转换为 TreeMap

2022-09-03 16:44:51
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

我知道如何使用转换为哈希映射

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

但是我需要 TreeMap with: Key - 具有最新消息的用户 senddate first Value - List 按 senddate 排序 最新最先

用户类的一部分

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

答案 1

您可以使用重载分组 By 方法并作为供应商传递:TreeMap

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

答案 2

如果您的列表已排序,则只需将此代码用于排序地图即可。

Map<String, List<WdHour>> pMonthlyDataMap = list
                .stream().collect(Collectors.groupingBy(WdHour::getName, TreeMap::new, Collectors.toList()));

推荐