我有一个for语句中的Java-7,它的做工精细:使用的if-else在Java的8 lambda表达式语句
Character cha = new Character(',');
String ncourseIds = null;
String pastCourseIds = null;
for (EquivalentCourse equivalentCourse : equivalentCourses) {
if(equivalentCourse.getNcourse() != null){
ncourseIds += equivalentCourse.getNcourse().getId()+ ",";
} else if(equivalentCourse.getPastCourse() != null) {
pastCourseIds +=equivalentCourse.getPastCourse().getId()+",";
}
}
if(!ncourseIds.isEmpty() &&cha.equals(ncourseIds.charAt(ncourseIds.length()-1))) {
ncourseIds = ncourseIds.substring(0, ncourseIds.length()-1);
}
if(!pastCourseIds.isEmpty()&& cha.equals(pastCourseIds.charAt(pastCourseIds.length()-1))) {
pastCourseIds = pastCourseIds.substring(0,pastCourseIds.length()-1);
}
现在,我想我的代码转换为Stream
& collect
在Java的8,我实现了我的业务的一半左右过滤器不为空Ncourse
:
equivalentCourses.stream().filter(obj -> obj.getNcourse() != null)
.map(obj -> obj.getNcourse().getId()).collect(Collectors.joining(","));
,但我不知道要实现它的else-statement
。任何帮助?
为什么你使用'Character'代替'char'?这会让你的代码更难阅读*和*浪费资源。尽管如此,如果用一个简单的'ncourseIds.endsWith(“,)代替'!ncourseIds.isEmpty()&& ha.equals(ncourseIds.charAt(ncourseIds.length() - 1))',你根本不需要它。 “)'同样,''pastCourseIds.isEmpty()&& cha.equals(pastCourseIds.charAt(pastCourseIds.length() - 1))''与'pastCourseIds.endsWith(”,“)'。要用流收集两个字符串,可以简单地执行两个流操作。 – Holger
@Holger已经说过:使用两个流操作(一个用于'getNcourse()!= null')和一个用于'getNcourse()== null && getPastCourse()!= null')。 –