优化 while(result.next()){ UserMsg userMsg = new UserMsg(); String user_id=result.getString("user_id"); String time=result.getString("time"); String msg=result.getString("msg"); userMsg.setMsg(msg); userMsg.setUser_id(user_id); userMsg.setTime(time); if(user!=user_id){ userMsg.setNum(0); }else{ userMsg.setNum(1); } list.add(userMsg); }
时间: 2023-06-12 19:03:43 浏览: 44
可以考虑使用Map来存储用户最新的一条消息,避免重复读取数据库。具体代码如下所示:
```
Map<String, UserMsg> latestMsgMap = new HashMap<>();
while (result.next()) {
String user_id = result.getString("user_id");
String time = result.getString("time");
String msg = result.getString("msg");
UserMsg userMsg = latestMsgMap.get(user_id);
if (userMsg == null || userMsg.getTime().compareTo(time) < 0) {
userMsg = new UserMsg();
userMsg.setUser_id(user_id);
userMsg.setTime(time);
userMsg.setMsg(msg);
latestMsgMap.put(user_id, userMsg);
}
}
for (UserMsg userMsg : latestMsgMap.values()) {
if (user.equals(userMsg.getUser_id())) {
userMsg.setNum(1);
} else {
userMsg.setNum(0);
}
list.add(userMsg);
}
```
该代码首先创建了一个空的HashMap,用于存储每个用户的最新消息。然后在遍历结果集时,对于每个用户,先从Map中获取最新的一条消息。如果Map中不存在该用户的消息,或者当前消息比Map中的消息更新,则将当前消息替换Map中的消息。最后,遍历Map中的每个用户的最新消息,根据当前用户是否为指定用户,设置Num属性,并将消息添加到list中。这样可以避免读取重复的消息,提高了程序的效率。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)