开发日记 2019.1.9

今天在优化代码的时候,发现了java8新增的stream在代码优化方面挺有效果,所以今天做个记录

原因:在遍历完的结果集中,有时会需要调用其他dubbo接口查询对应的字段

private List getAchievementTree() {
	List parentList = selectParentRewards();
		for (int i = 0; i < parentList.size(); i++) {
			TbAchievementRewards tbAchievementRewards = parentList.get(i);
			List childrenList = tbAchievementRewardsMapper
					.findRewardsByParentId(tbAchievementRewards.getId());
			tbAchievementRewards.setChildrenList(childrenList);
			parentList.set(i, tbAchievementRewards);
		}
		return parentList;
}

像这种情况的话如果数据量一旦多了会对服务器造成负担,所以我选择先将需要查询的AchievementRewards作为一个map集合查询一次,将rewardid为key,AchievementRewards为值保存下来,遍历时直接从map中查,作用类似与redis,但由于使用redis要经常在修改字段时更新redis数据,所以放弃了。
使用java8新增的stream后,代码为

private List getAchievementTree() {
		List parentList = selectParentRewards();
		List selectList = tbAchievementRewardsMapper.selectList(
				new QueryWrapper().eq("delete_flag", 0).orderByAsc("complete_condition"));
		Map> childrenMap = selectList.stream()
				.collect(Collectors.groupingBy(TbAchievementRewards::getAchievementType));
		for (int i = 0; i < parentList.size(); i++) {
			TbAchievementRewards tbAchievementRewards = parentList.get(i);
			List childrenList = childrenMap.get(tbAchievementRewards.getId());
			tbAchievementRewards.setChildrenList(childrenList);
			parentList.set(i, tbAchievementRewards);
		}
		return parentList;
}

其中
selectList.stream().collect(Collectors.groupingBy(TbAchievementRewards::getAchievementType))的意思是,将selectList通过AchievementType属性分成一个map,map中key为AchievementType,value为TbAchievementRewards的List集合,这样我调用时直接通过 map的get方法就可以获得对应的list集合了,java8新增的stream当然不止这些功能,具体的留个链接备忘https://blog.csdn.net/young4dream/article/details/76794659

你可能感兴趣的:(开发日记 2019.1.9)