Stream 获取去重 转换Map 数据转换

	//        获取去重的评论人
		Set<Long> commentators = comments.stream().map(comment -> comment.getCommentator()).collect(Collectors.toSet());
		List<Long> userIds = new ArrayList<>();
		userIds.addAll(commentators);
	
	//       获取评论人并转换成Map
		UserExample userExample = new UserExample();
		userExample.createCriteria()
					.andIdIn(userIds);
		List<User> users = userMapper.selectByExample(userExample);
		Map<Long, User> userMap = users.stream().collect(Collectors.toMap(user -> user.getId(), user -> user));
	
	//       转换comment为commentDTO
		List<CommentDTO> commentDTOS = comments.stream().map(comment -> {
			CommentDTO commentDTO = new CommentDTO();
			BeanUtils.copyProperties(comment, commentDTO);
			commentDTO.setUser(userMap.get(comment.getCommentator()));
			return commentDTO;
		}).collect(Collectors.toList());
		return commentDTOS;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用Java 8的Stream获取某列去重集合,可以按照以下步骤进行操作: 1. 首先,确保你有一个包含要处理的对象的List集合,例如Book类的List<Book> books。 2. 然后,使用stream()方法将List转换Stream,例如books.stream()。 3. 接下来,使用map()方法将每个对象映射到要去重的列,例如getName()方法获取每本书的名称。 4. 使用distinct()方法来去掉重复的元素,例如books.stream().map(Book::getName).distinct()。 5. 最后,将结果转换回List集合,可以使用collect()方法并结合Collectors.toList(),例如books.stream().map(Book::getName).distinct().collect(Collectors.toList())。 另外,如果你希望根据某个特定的字段进行去重,你可以使用Collectors.toCollection()方法,并在构造函数中指定字段,例如new TreeSet<>(Comparator.comparing(o -> o.getName()))。这样可以确保根据名称字段进行比较去重。例如: List<Book> distinctNameBooks = books.stream() .collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Book::getName))), ArrayList::new)); System.out.println(distinctNameBooks); 这样就可以通过Stream获取某列的去重集合了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [List列表运用Java8的stream流按某字段去重](https://blog.csdn.net/weixin_39377712/article/details/123566116)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值