Home > other >  How do I turn this expression into a lambda expression?
How do I turn this expression into a lambda expression?

Time:11-18

I'd like to turn what I'm doing into lambda, in which case it would be I scroll through a list (listRegistrationTypeWork) within the other, check if the child list (getRegistrationTypeWorkAuthors) is != null, if it is, scroll through it looking for an authorCoautor = type, and increment a count, to find out how many records within the lists have this same type.

public int qtyMaximumWorksByAuthorCoauthor(AuthorCoauthor type) {
    int count = 0;
    for (RegistrationTypeWork tab : listRegistrationTypeWork) {
        if (CollectionUtils.isNotEmpty(tab.getRegistrationTypeWorkAuthors())) {
            for (RegistrationTypeWorkAuthors author : tab.getRegistrationTypeWorkAuthors()) {
                if (author.getAuthorCoauthor().equals(type))
                    count  ;
            }
        }
    }
    return count;
}

CodePudding user response:

Although your statement is not clear enough on what transforming to lambda expression would mean, but I am assuming you would like to turn your imperative looping step to a functional stream and lambda based one.

This should be straightforward using:

  • filter to filter out the unwanted values from both of your collections
  • flatMap to flatten all inner collections into a single stream so that you can operate your count on it as a single source
public int qtyMaximumWorksByAuthorCoauthor(AuthorCoauthor type) {
    return listRegistrationTypeWork.stream()
            .filter(tab -> tab.getRegistrationTypeWorkAuthors() != null)
            .flatMap(tab -> tab.getRegistrationTypeWorkAuthors().stream())
            .filter(author -> type.equals(author.getAuthorCoauthor()))
            .count();
}

CodePudding user response:

In addition to Thomas fine comment I think you would want to write your stream something like this.


long count = listRegistrationTypeWork.stream()
  // to make sure no lists that are actual null are mapped.
  // map all RegistrationTypeWork into optionals of lists of RegistrationTypeWorkAuthors
  .map(registrationTypeWork -> Optional.ofNullable(registrationTypeWork.getRegistrationTypeWorkAuthors()))
  // this removes all empty Optionals from the stream
  .flatMap(Optional::stream)
  // this turns the stream of lists of RegistrationTypeWorkAuthors into a stream of plain RegistrationTypeWorkAuthors
  .flatMap(Collection::stream)
  // this filters out RegistrationTypeWorkAuthors which are of a different type
  .filter(registrationTypeWorkAuthors -> type.equals(registrationTypeWorkAuthors.getAuthorCoauthor()))
  .count();

// count returns a long so you either need to return a long in your method signature or cast the long to an integer.
 return (int) count;
  • Related