javalambdaifelse_在java-8lambda表达式中使⽤if-else语句我在java-7中有⼀个for语句,它的⼯作正常:
Character cha = new Character(',');
String ncourseIds = null;
String pastCourseIds = null;
for (EquivalentCourse equivalentCourse : equivalentCourses) {
Ncourse() != null){
ncourseIds += Ncourse().getId()+ ",";
} else PastCourse() != null) {java stream
pastCourseIds +=PastCourse().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&在java-8中收集,我实现了我的⼀半业务关于过滤器⽽不是null Ncourse:
equivalentCourses.stream().filter(obj -> Ncourse() != null )
.map(obj -> Ncourse().getId()).collect(Collectors.joining(","));
但我不知道要实施它的其他声明.任何帮助?
解决⽅法:
由于流调⽤链很复杂,因此需要两个流 – 避免条件分⽀.
String ncourseIds = equivalentCourses.stream()
.filter(equivalentCourse -> Ncourse() != null)
.map(EquivalentCourse::getNcourse)
.map(x -> String.Id()))
.collect(Collectors.joining(", "));
String pastCourseIds = equivalentCourses.stream()
.filter(equivalentCourse -> Ncourse() == null
&& PastCourse() != null)
.map(EquivalentCourse::getPastCourse)
.map(x -> String.Id()))
.
collect(Collectors.joining(", "));
这也是专注于⽣成的两个字符串的代码,具有⾼效的连接.
顺便说⼀句,如果这是⼀个SQL字符串,您可以使⽤带有Array的PreparedStatement.由@Holger评论的点缀:
String ncourseIds = equivalentCourses.stream()
.map(EquivalentCourse::getNcourse)
.filter(Objects::nonNull)
.map(NCourse::getId)
.map(String::valueOf)
.collect(Collectors.joining(", "));
String pastCourseIds = equivalentCourses.stream()
.filter(equivalentCourse -> Ncourse() == null)
.map(EquivalentCourse::getPastCourse)
.filter(Objects::nonNull)
.map(EquivalentCourse::getPastCourse)
.map(PastCourse::getId)
.map(String::valueOf)
.collect(Collectors.joining(", "));
标签:java,lambda,if-statement,java-8

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。