Search code examples
javaspringspring-datajava-stream

How to rid of code duplication when two similar repositories?


Upon given type I want to retrieve data from either one or another repority. This is what I came up with:

        if (type.equals("first")) {
            codes = firstRepository.findAll().stream()
                    .map(numbers::getCode)
                    .collect(Collectors.toList());
        } else {
            codes = secondRepository.findAll().stream()
                    .map(numbers::getCode)
                    .collect(Collectors.toList());
        }

Now I am looking for an elegant solution to remove the code duplication.


Solution

  • Something like this ?

    codes = (type.equals("first") ? firstRepository : secondRepository).findAll().stream()
        .map(numbers::getCode)
        .collect(Collectors.toList());