Pankaj
Pankaj

Reputation: 3674

Handle null or empty collection with Java 8 streams

I have collection of company and each company has list of department and department which are filtered based on complex multilevel condition. I would like to get the department info from some other source when there is no department found in a company and then proceed with filter condition as next step. Is the below implementation best way to achieve ?

   public class Company{
     private List<Department> departments;
   }

       companies.stream().forEach(c -> {
            if(CollectionUtils.isEmpty(c.getDepartments())){
                //handle no department 
                //Set the department after getting from different source
            }
        });
 
companies.stream()
    .filter(c -> CollectionUtils.isNotEmpty(c.getDepartments()))
    .filter(c -> c.getDepartments().stream()
            .anyMatch(d -> condition))
    .collect(Collectors.toList());

Upvotes: 1

Views: 1054

Answers (1)

Eugene
Eugene

Reputation: 121048

You can do the if/else statement in you code as suggested already. If you want your colleagues to look weird at you (who does not like that?), you could write it as:

companies.stream()
         .map(x -> Optional.ofNullable(x.getDepartments())
                           .flatMap(dep -> dep.size() == 0 ? Optional.empty() : Optional.of(dep))
                           .orElse(List.of()) // get it from another source...
        ).filter(...)

Upvotes: 1

Related Questions