这是我的代码:/* Returns a Map that stores a contact name as a key and a list of messages from that contactas 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]
2 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
看来您想使用 Collectors.groupingBy。即按键分组而不是对键进行排序。
Map<String, List<Message>> map = messages.stream() .filter(t -> t.getContact().isPresent()) .collect(Collectors.groupingBy(mg -> mg.getContact().get()));
桃花长相依
TA贡献1860条经验 获得超8个赞
使用 TreeMap 类而不是 HashMap。
Map<String, List<Message>> map = new TreeMap<String, List<Message>>();
TreeMap 是按键排序的。在您的情况下,地图的键是字符串,因此它将按字母顺序排序。
添加回答
举报
0/150
提交
取消