public Map> groupList(List list){
//定义一个map集合用于分组
Map> mapList = new HashMap>();
//遍历集合以message的 toId和fromId组合为键,以message为值保存到mapList中
for (Iterator it = list.iterator(); it.hasNext();){
//将循环读取的结果放入对象中
Message message = (Message) it.next();
//如果在这个map中包含有相同的键,这创建一个集合将其存起来
if (mapList.containsKey(message.getToId()+"-"+message.getFromId()+"-")){
List syn = mapList.get(message.getToId()+"-"+message.getFromId()+"-");
syn.add(message);
}else if(mapList.containsKey(message.getFromId()+"-"+message.getToId()+"-")){
List syn = mapList.get(message.getFromId()+"-"+message.getToId()+"-");
syn.add(message);
} else {//如果没有包含相同的键,在创建一个集合保存数据
List newList = new ArrayList();
newList.add(message);
mapList.put(message.getFromId()+"-"+message.getToId()+"-", newList);
}
}
return mapList;
}
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID",nullable = false)
private Long id;//主键ID
@Column(name="ToID",nullable = false)
private Long toId;//接收方UserId
@Column(name="FromId",nullable = false)
private Long fromId;//发送方UserID
@Column(name="Content",nullable = true)
private String content;//消息内容
@Column(name="Status",nullable = false)
private String status;//状态:unread未读,read 已读
@Column(name="AddTime",nullable = false)
private Timestamp addTime;//添加时间
get/set……方法省略