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 进行转换
list.stream().collect(Collectors.groupingBy(Message::getSender));
但我需要 TreeMap 与: 键 - 最新消息发送日期第一的用户 值 - 列表按发送日期最新排序
用户类的一部分
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());
}
}