微服务之间调用外键“翻译”的方法概述
写在前面的话:减少strean流操作,减少多层嵌套for循环。使用普通for循环和map的方式进行转换,
第一步查询数据
List<Student> findList = studentDao.findList(findMap);
第二步准备遍历和赋值
if(CollectionUtil.isNotEmpty(findList)){
// 第一次遍历,取出所有待翻译的字段,避免重复使用steam流取值
Set<String> courseSet = new HashSet<>(16);
Set<String> schooldSet = new HashSet<>(16);
Set<String> nativePlaceSet = new HashSet<>(16);
for (Student student : findList) {
// 课程id
String courseId = student.getSourceId();
if(StringUtil.isNotEmpty(courseId)){
courseSet.add(courseId);
}
// 学校id
String schooldId = student.getSchoold();
if(StringUtil.isNotEmpty(schooldId)){
schooldSet.add(schooldId);
}
// 籍贯id
String nativePlaceId = student.getNativePlace();
if(StringUtil.isNotEmpty(nativePlaceId)){
nativePlaceSet.add(nativePlaceId);
}
}
// 查询课程信息、学校信息、籍贯信息,并转换成map
Map<String,Object> findMap = new HashMap<>(16);
findMap.put("courseSet",courseSet);
findMap.put("schooldSet",schooldSet);
findMap.put("nativePlaceSet",nativePlaceSet);
List<Course> courseList = courseDao.findList(findMap);
List<Schoold> schooldList = schooldDao.findList(findMap);
List<NativePlace> nativePlaceList = nativePlaceDao.findList(findMap);
// 转换成map
Map<String,Course> courseMap = CollectionUtil.isEmpty(courseList) ? new HashMap<>(0) :
courseList.stream().collect(Collectors.toMap(Course::getId, course -> course));
Map<String,Schoold> schooldMap = CollectionUtil.isEmpty(schooldList) ? new HashMap<>(0) :
courseList.stream().collect(Collectors.toMap(Schoold::getId, schoold -> schoold));
Map<String,NativePlace> nativePlaceMap = CollectionUtil.isEmpty(nativePlaceList) ? new HashMap<>(0) :
courseList.stream().collect(Collectors.toMap(NativePlace::getId, nativePlace -> nativePlace));
// 第二次遍历,填充翻译后的值
for (Student student : findList) {
// 课程id-->课程名称
String courseId = student.getSourceId();
if(StringUtil.isNotEmpty(courseId)){
student.setSourceName(courseMap.get(courseId).getName());
}
// 学校id-->学校名称
String schooldId = student.getSchoold();
if(StringUtil.isNotEmpty(schooldId)){
student.setSchooldName(schooldMap.get(schooldId).getName());
}
// 籍贯id-->籍贯名称
String nativePlaceId = student.getNativePlace();
if(StringUtil.isNotEmpty(nativePlaceId)){
student.setNativePlaceName(nativePlaceMap.get(nativePlaceId).getName());
}
}
}
结语:仅遍历2次,减少了stream流取值。用转map的方式减少了多层for循环。