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