12

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

2 Answers 2

11

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()); 
Sign up to request clarification or add additional context in comments.

1 Comment

institutionUserConnectionService.getActiveInstitutionUserConnectionsByInstitution(institution) throws an Exception. Is there also a possibility to handle this? Thanks a lot!
6

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

1 Comment

Reference to 'addAll' is ambiguous, both 'addAll(Collection<? extends E>)' and 'addAll(int, Collection<? extends E>)' match

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.