简体   繁体   中英

Java-8 addAll Objects

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));
}

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());

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; }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM