现在对于集合操作时,我都是使用Stream来进行操作的,感觉贼好用,对于map操作时,一般使用方法引用就能解决,如
gradeList.stream()
.map(RegionGradeViewForm::getRegionId)
.map(String::valueOf)
.collect(toList());
Stream流配合方法引用写的代码看着就舒服,所以用久了就不想看见箭头符号,但是在操作filter的时候,因为需要进行复杂的判断,方法引用就不适用了,如这样的代码
studentList.stream()
.filter(student -> !hasTemperatures.contains(student.getStudentId()))
.sorted(Comparator.comparing(StudentEntity::getStudentClass))
.collect(toList());
Map<Integer, String> gradeNameByClassIdCache = classList.stream()
.filter(classView ->{
if(classView.getClassLevelId() == null){
return false;
}
return true;
})
.collect(toMap(ClassViewForm::getClassId, classView ->{
Integer levelId = classView.getClassLevelId();
return gradeNameCache.get(String.valueOf(levelId));
}));
用的多了感觉不美观,发现guava Predicates工具类能够优雅解决这个问题
对于第一个式子
studentList.stream()
.filter(Predicates.compose(hasTemperatures::contains, StudentEntity::getStudentId).negate())
.sorted(Comparator.comparing(StudentEntity::getStudentClass))
.collect(toList());
对于第二个式子
Map<Integer, String> gradeNameByClassIdCache = classList.stream()
.filter(Predicates.compose(Objects::isNull, ClassViewForm::getClassLevelId).negate())
.collect(toMap(ClassViewForm::getClassId, classView ->{
Integer levelId = classView.getClassLevelId();
return gradeNameCache.get(String.valueOf(levelId));
}));
我感觉在Stream流操作集合时,尽量使用方法引用进行操作,这样使得代码简短,还美观,相应的Predicates类的方法还有多少,这里就不一一介绍了,只要熟悉Predicate接口的同学应该看一眼就知道怎么用了。
另外guava还提供了Functions工具类,来处理Function接口的方法,这个也可以在Stream流中进行操作,下次再进行Stream操作时,可以先留意这两个类。