有谁能帮我处理一下流等效代码吗注意:-我不能设置studentFinalList "final">
List<Student> studentFinalList=new ArrayList<>();
for (Student ep:StudentList) {
if (StringUtils.isBlank(ep.getName()) && ep.getName() == null) {
studentFinalList.add(ep);
}
else if (StringUtils.isNotBlank(ep.getName()) &&
!ep.getName().equals("") && ep.getName() != null) {
if (sIdList.contains(ep.getId())) {
studentFinalList.add(ep);
}
}
}
代码中的一些条件似乎是多余的,可以在不影响逻辑的情况下删除:
StringUtils.isBlank(ep.getName()) && ep.getName() == null
可以缩短为ep.getName() == null
-因为StringUtils.isBlank
检查null,空或仅为空白的字符串StringUtils.isNotBlank(ep.getName()) && !ep.getName().equals("") && ep.getName() != null
-没有必要检查!name.equals("")
和null
,所以只有StringUtils.isNotBlank(ep.getName())
是足够的。
接下来,将id列表sIdList
转换为set,以方便查找id (O(1)
在sets中而不是O(N)
在list中)。
Set<String> sIdSet = new HashSet<>(sIdList);
List<Student> studentFinalList = studentList
.stream()
.filter(ep -> ep.getName() == null
|| (!StringUtils.isBlank(ep.getName()) && sIdSet.contains(ep.getId()))
)
.collect(Collectors.toList());
您可以将所有if语句放在一个filter
:
List<Student> studentFinalList = studentList.stream()
.filter(ep -> (StringUtils.isBlank(ep.getName()) && ep.ep.getName() == null) ||
(StringUtils.isNotBlank(ep.getName()) && !ep.getName().equals("") &&
ep.getName() != null && sIdList.contains(ep.getId())))
.collect(Collectors.toList());
虽然我建议仔细检查你提交的代码,因为我怀疑它包含一些错误,例如ep.ep.getName()
。