根据java中的键对地图的值进行排序

这是我的代码:


/* Returns a Map that stores a contact name as a key and a list of messages from that contact

as a value. If a message has no associated contact, it should not appear in the Map. Must 

not change messages field. Must call filter with an anonymous inner class in the method body. */

public Map<String, List<Message>> sortMessagesByContact() {

    Map<String, List<Message>> map = new HashMap<>();

    List<Message> filtered = new ArrayList<>();


    Predicate<Message> p = new Predicate<>() {

        @Override

        public boolean test(Message t) {

            return t.getContact().isPresent();

        }

    }; for (Message mg : messages) {

        if (p.test(mg)) {

            map.put(mg.getContact().get(), messages);

        }

    }

    return map;

}

这是我到目前为止所得到的。但我无法想出一种方法来将来自该联系人的消息列表作为值。顺便说一句,我应该在这里使用匿名内部类


例如,当打印带有四条消息的地图时,


我应该得到这样的东西:


James = [bakjd],[adjlfaj],[daklfja], Howard = [dajfkla]


白板的微信
浏览 161回答 2
2回答

宝慕林4294392

看来您想使用 Collectors.groupingBy。即按键分组而不是对键进行排序。Map<String,&nbsp;List<Message>>&nbsp;map&nbsp;=&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;messages.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(t&nbsp;->&nbsp;t.getContact().isPresent()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.groupingBy(mg&nbsp;->&nbsp;mg.getContact().get()));

桃花长相依

使用 TreeMap 类而不是 HashMap。Map<String, List<Message>> map = new TreeMap<String, List<Message>>();TreeMap 是按键排序的。在您的情况下,地图的键是字符串,因此它将按字母顺序排序。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java