Java 8 Stream API toMap converting to TreeMap

后端 未结 2 1635
耶瑟儿~
耶瑟儿~ 2021-02-05 17:35
public class Message {
    private int id;
    private User sender;
    private User receiver;
    private String text;   
    private Date senddate;
..
}
相关标签:
2条回答
  • 2021-02-05 18:03

    If your list is sorted then just use this code for sorted map.

    Map<String, List<WdHour>> pMonthlyDataMap = list
                    .stream().collect(Collectors.groupingBy(WdHour::getName, TreeMap::new, Collectors.toList()));
    
    0 讨论(0)
  • 2021-02-05 18:21

    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()));
    
    0 讨论(0)
提交回复
热议问题