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; }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With