Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-8 addAll Objects

Tags:

java

java-8

Is there a better way of doing this in Java 8?

final List<InstitutionUserConnection> allInstitutionUserConnections = new ArrayList<>();
for (final Institution institution : institutionsOfUser) {
    allInstitutionUserConnections
        .addAll(institutionUserConnectionService.getActiveInstitutionUserConnectionsByInstitution(institution));
}
like image 549
quma Avatar asked Mar 18 '16 11:03

quma


2 Answers

Yes, this is what the flatMap operation is for:

List<InstitutionUserConnection> allInstitutionUserConnections =
    institutionsOfUser.stream()
                      .flatMap(institution -> institutionUserConnectionService.getActiveInstitutionUserConnectionsByInstitution(institution).stream())
                      .collect(Collectors.toList());

If the method throws a checked exception, then you need to catch it and handle it with logging, rethrowing an unchecked exception and/or returning a default value.

List<InstitutionUserConnection> allInstitutionUserConnections =
    institutionsOfUser.stream()
                      .flatMap(institution -> {
                          try {
                              return institutionUserConnectionService.getActiveInstitutionUserConnectionsByInstitution(institution).stream();
                          } catch (TheCheckedThrownException e) {
                              // do something here, like throw an unchecked exception
                          }
                      })
                      .collect(Collectors.toList());
like image 143
Tunaki Avatar answered Sep 30 '22 19:09

Tunaki


Instead of flat mapping the inner list to a stream, you can also map it directly to a List, and then use a custom collector to append the element. The advantage of using a collector above using the stream, is that using a collector, you can get higher performance because the fact it uses 1 large addAll call, instead of separate small add calls like the Collectors.toList() does.

A solution based on this looks like:

List<InstitutionUserConnection> result = institutionsOfUser.stream().
        .map(institutionUserConnectionService::getActiveInstitutionUserConnectionsByInstitution)
        .collect(Collector.of(ArrayList::new, List::addAll,
                (left, right) -> { left.addAll(right); return left; }));
like image 42
Ferrybig Avatar answered Sep 30 '22 20:09

Ferrybig