Can anyone help me with the stream equivalent code Note:- I cannot make the studentFinalList “final”
JavaScript
x
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);
}
}
}
Advertisement
Answer
Some conditions in the code seem to be redundant and may be removed without affecting the logic:
StringUtils.isBlank(ep.getName()) && ep.getName() == null
may be shortened toep.getName() == null
– becauseStringUtils.isBlank
checks for null, empty, or whitespace-only stringStringUtils.isNotBlank(ep.getName()) && !ep.getName().equals("") && ep.getName() != null
– there’s no need to check for!name.equals("")
andnull
so onlyStringUtils.isNotBlank(ep.getName())
is enough.
Next, list of ids sIdList
should be converted into set to facilitate look-up of the ids (O(1)
in sets instead of O(N)
in list).
Thus, the code may ne simplified as:
JavaScript
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());