user2586917
user2586917

Reputation: 774

Better idiom for listing inner items of a 1-to-N-to-1 relationship?

I have the following model:

1 RepositoryDTO can have many ResourceDTOs, and in each ResourceDTO is exacly one TeamDTO.

So to get the TeamDTOs from the RepositoryDTO, I am doing the following:

RepositoryDTO repoDTO = ...
List<TeamDTO> teamsLinkedToRepo = getTeamsLinkedTo(repoDTO);

private List<TeamDTO> getTeamsLinkedTo(final RepositoryDTO repository) {
    final List<TeamDTO> teamsLinkedToRepository = new ArrayList<TeamDTO>();
    for (final ResourceDTO resourceDTO : repository.getResources()) {
      teamsLinkedToRepository.add(resourceDTO.getTeam());
    }
    return teamsLinkedToRepository;
}

I'm just wondering is there a better idiom for doing this, maybe using Google Guava?

Upvotes: 5

Views: 159

Answers (2)

Caleryn
Caleryn

Reputation: 1084

Good code as Chris states, only one minor change if and only if possible and if the number of teams is potentially large you may wish to consider initialising the new ArrayList using new ArrayList(Integer), to avoid the underlying array being rebuilt. Potentially:

  new ArrayList<TeamDTO>(repository.getResources().size());

Upvotes: 1

Christian Strempfer
Christian Strempfer

Reputation: 7383

Keep simple things simple.

We used Google Guava excessively in one of our projects. And while it was less code and faster to read, it became a nightmare when debugging. So I advice to not use it until you get an huge advantage from it (and simple for-loops won't get any better with it).

With pure Java it's good code. There is no need to improve it.

Upvotes: 8

Related Questions