S
S
Snoyter2021-05-27 10:16:51
Java
Snoyter, 2021-05-27 10:16:51

How to optimize this code setting?

How to optimize this query so that you need to go to the database only once and get a map from the product Id key and the value true if there is a license in the database.

Method receiving code:

Map<Integer, Boolean> license = new HashMap<>();

       for (OverviewOffer offer: offers) {
            license.put(offer.getId(), licenseRepository.loadById(offer.getId()).equals(1));
        }


Pseudo code for accessing the database:
public Integer loadById(Integer id) {
       
        return id % 2 == 0 ? true : false ;
    }


As you can see, I go to the database through a loop, which is bad, but nothing comes to mind, how to arrange it correctly.
Tried something like this
Map<Integer, Boolean> license = licenseRepository.loadByReferenceIds(ids).stream().collect(Collectors.toMap(Offer::getId, Должен быть Boolean))
But xs how to put the Boolean itself into a value.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-05-27
@Snoyter

Something like this:

class Example {
    public static void main(String[] args) {
        var licenses = List.of(
                new License(1, true),
                new License(2, false),
                new License(3, true)
                );
        
        var licenseMap = licenses.stream()
                .collect(Collectors.toMap(License::getId, License::isActive));
    }

    @Getter
    @RequiredArgsConstructor
    private static class License {
        private final Integer id;
        private final boolean isActive;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question