1

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());
5
  • That won't compile because forEach returns void. Are you trying to return a list of new companies that are modified versions of the existing ones? Or do you want to mutate the existing companies? Is the list newCompanies going to contain the same number of companies as the original list companies?
    – k314159
    Commented May 6, 2021 at 21:47
  • 2
    so why can't you chain that directly via a map(department -> if(...) return from other source; else return departments).filter(...)
    – Eugene
    Commented May 6, 2021 at 21:50
  • @k314159 my bad.. fixed it .. I will add the missing grant to the company by getting from different source.. I have updated the post
    – Pankaj
    Commented May 6, 2021 at 21:58
  • @Eugene Let me try what you suggested..
    – Pankaj
    Commented May 6, 2021 at 22:02
  • @Eugene This works ..thanks a lot for the pointer
    – Pankaj
    Commented May 6, 2021 at 22:42

1 Answer 1

1

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(...)
2
  • 1. With the current code in the question the return type is a List of Company and not Department. 2. dep.size() == 0 => dep.isEmpty or you could even filter out empty collections after nullable.
    – Naman
    Commented May 7, 2021 at 3:22
  • 1
    flatMap(dep -> dep.size() == 0 ? Optional.empty() : Optional.of(dep)) is a very twisted way of saying filter(dep -> !dep.isEmpty()). On the other hand, the entire construct is an unnecessarily complicated way of saying x -> { var dep = x.getDepartments(); if(dep == null || dep.isEmpty()) dep = …; return dep; }
    – Holger
    Commented May 7, 2021 at 8:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.