@RequestMapping(value = "/songList", method = RequestMethod.GET) public Object recommendSongList(HttpServletRequest req, @RequestParam(value = "userId",defaultValue = " ") String userId){ System.out.println("-------------userId=" + userId); //如果userId为空就返回所有歌单 if(StringUtils.isBlank(userId)) { return songListService.allSongList(); }else{ return recommendSongListService.recommendSongListByCollect(Integer.parseInt(userId)); } } 如何为该段添加去重
时间: 2023-12-12 19:02:34 浏览: 29
可以考虑使用Set数据结构来实现去重。具体做法是,在获取推荐歌单之前,先将用户已收藏的歌单ID存入一个Set集合中,再在获取推荐歌单时,遍历每个歌单的ID,判断是否在Set集合中出现过,如果出现过就跳过,否则将该歌单ID加入Set集合,并将该歌单加入推荐列表中。修改后的代码如下:
```
@RequestMapping(value = "/songList", method = RequestMethod.GET)
public Object recommendSongList(HttpServletRequest req, @RequestParam(value = "userId",defaultValue = " ") String userId){
System.out.println("-------------userId=" + userId);
//如果userId为空就返回所有歌单
if(StringUtils.isBlank(userId)) {
return songListService.allSongList();
}else{
Set<Integer> collectedSongListIds = recommendSongListService.getCollectedSongListIds(Integer.parseInt(userId)); // 获取用户已收藏的歌单ID集合
List<SongList> recommendSongList = new ArrayList<>(); // 推荐歌单列表
for(SongList songList : recommendSongListService.recommendSongListByCollect(Integer.parseInt(userId))) { // 遍历每个推荐歌单
if(!collectedSongListIds.contains(songList.getId())) { // 判断该歌单ID是否已被收藏过
collectedSongListIds.add(songList.getId()); // 将该歌单ID加入已收藏的ID集合
recommendSongList.add(songList); // 将该歌单加入推荐列表
}
}
return recommendSongList;
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)