Java 8 Stream API toMap转换为TreeMap

时间:2016-01-31 16:33:59

标签: java lambda java-8 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
list.stream().collect(Collectors.groupingBy(Message::getSender));

但我需要TreeMap:  密钥 - 具有最新消息的用户首先发送日期 价值 - 列表按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());
        }
    }

2 个答案:

答案 0 :(得分:17)

您可以使用重载groupingBy方法并将TreeMap作为Supplier传递:

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

答案 1 :(得分:2)

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

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