Skip to content
Advertisement

Need a equivalent code in java streams for iterating list of Object

Can anyone help me with the stream equivalent code Note:- I cannot make the 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);
        }
    }
}

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 to ep.getName() == null – because StringUtils.isBlank checks for null, empty, or whitespace-only string
  • StringUtils.isNotBlank(ep.getName()) && !ep.getName().equals("") && ep.getName() != null – there’s no need to check for !name.equals("") and null so only StringUtils.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:

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());
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement