在一些评论列表存在回复情况下,如何构建返回的数据呢?下面是简单的实现逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
@Override public List<InstantChatChannelCommentVo> getInstantChatChannelCommentList(String channelId, String userId, Integer pageCurrent, Integer pageSize) throws InvocationTargetException, IllegalAccessException { if (StringUtils.isEmpty(channelId)) { throw new IllegalArgumentException("频道id不能为空"); } PlatInstantChatChannelEntity channel = platInstantChatChannelService.getInstantChatChannelDetail(channelId); if (channel == null) { throw new RuntimeException("频道不存在"); } String channelType = channel.getChannelType(); if (StringUtils.isEmpty(channelType)) { throw new RuntimeException("频道类型不能为空"); } if (!channelType.equals(InstantChatChannelTypeEnum.COMMENT_CHANNEL.getCode())) { throw new RuntimeException("该频道不支持评论"); } List<PlatInstantChatChannelCommentEntity> commentList = this.getInstantsChatChannelCommentList(channelId, pageCurrent, pageSize); List<String> commentIds = commentList.stream().map(PlatInstantChatChannelCommentEntity::getId).collect(Collectors.toList()); List<PlatInstantChatChannelCommentEntity> replyList = this.getInstantsChatChannelCommentReplyList(commentIds);
Map<String, InstantChatChannelCommentVo> commentTreeMap = new TreeMap<>();
for (PlatInstantChatChannelCommentEntity comment : commentList) { InstantChatChannelCommentVo vo = new InstantChatChannelCommentVo(); BeanUtils.copyProperties(vo, comment); commentTreeMap.put(comment.getId(), vo); }
for (PlatInstantChatChannelCommentEntity reply : replyList) { String parentId = reply.getParentId(); if (StringUtils.isEmpty(parentId)) { continue; } if (!commentTreeMap.containsKey(parentId)) { continue; } List<InstantChatChannelCommentVo> parentReplyList = commentTreeMap.get(parentId).getReplyList(); if (parentReplyList == null) { parentReplyList = new ArrayList<>(); commentTreeMap.get(parentId).setReplyList(parentReplyList); } InstantChatChannelCommentVo vo = new InstantChatChannelCommentVo(); BeanUtils.copyProperties(vo, reply); commentTreeMap.get(parentId).getReplyList().add(vo); } List<InstantChatChannelCommentVo> commentVos = new ArrayList<>(commentTreeMap.values()); commentVos.sort(Comparator.comparing(InstantChatChannelCommentVo::getCreateTime).reversed()); return commentVos; }
|
- 首先分页获取评论列表
- 根据评论列表 ID 集合获取关联的回复列表(这里可以根据实际情况返回条数或做分页,后续异步获取更多回复记录,此处直接获取所有回复记录)
- 构造 TreeMap 存放评论记录
- 遍历评论记录,构建评论、回复二级树
- 将 TreeMap 转为 List 返回(这里按实际情况处理)
以上步骤可能有点冗余,可视实际情况优化。
END