您可以拥有一个Map
Apache Collections。CircularFifoBuffer
//maps username to last 5 messages
Map<String,CircularFifoBuffer> map = new HashMap<String,CircularFifoBuffer>();
//putting the values
if(map.get(username) == null){
CircularFifoBuffer last5messages = new CircularFifoBuffer(5);
last5messages.add(message);
map.put(last5messages);
}else{
//similar code
}
什么是 CircularFifoBuffer?
CircularFifoBuffer 是一个具有固定大小的先进先出缓冲区,如果已满则替换其最旧的元素。
这样会自动存储最后 5 条消息,从缓冲区中删除最旧的消息。
编辑:
根据我对评论的理解:
让我告诉你我的意思 Bob:嗨 Bob:我很无聊 :l Joseph:哦,嘿嘿 Josephary:嘿 Joseph 和 Bob Joseph:哦,你们两个好吗?
class MessageEntry{
String userName;
String message;
public MessageEntry(String userName, String message){
//store
}
public String getUsername(){
return userName;
}
public String getMessage(){
return message;
}
}
//just a buffer to store last 5 messages received
CircularFifoBuffer last5messages = new CircularFifoBuffer(5);
//for storing last 5 messages
last5messages.add(new MessageEntry(userName,message));
//for retrieving elements:
Object[] messages = last5Messages.toArray();
//gives you messages that you can use any way you want
for(Object message : messages){
MessageEntry entry = (MessageEntry)message;
String userName = entry.getUsername();
String message = entry.getMessage();
}