Simple local cache that checks by date else get from db I'm looking for feedback on how this can be improved. Basically what I'm trying to do is check if the cache has the object, else check from the database.

I have a list of ids, then I separate them based on whether they already exist in the cache or not, based on the date as well. One list fetches from the cache, the other from the db. Then return the list. That way I don't have to make multiple calls to cache/db.

The alternative is to implement a compound-key, but I would rather not go that route.

https://github.com/mel3kings/taxi-cab-api/blob/master/src/main/java/com/simple/controller/CabController.java

 private List&lt;Cab&gt; getFromCacheOrDb(CabTripsRequest request) {
        Map&lt;Boolean, List&lt;String&gt;&gt; cachedCabs = request.getMedallions().stream().collect(
                partitioningBy(key -&gt; {
                    if (!cache.peek(key)) { return false; }
                    return cache.get(key).stream().anyMatch(a -&gt; a.getPickupDateTime().equals(request.getDate()));
                }));
        List&lt;Cab&gt; response = cachedCabs.get(true).stream().map(k -&gt; cache.get(k)).flatMap(List::stream)
                .filter(cab -&gt; cab.getPickupDateTime().equals(request.getDate())).collect(toList());
        if (cachedCabs.get(false).size() &gt; 0) {
            List&lt;Cab&gt; database = storage.fetch(cachedCabs.get(false), request.getDate());
            response.addAll(database);
            cache.save(database);
        }
        log.info("response from cache/db size:" + response.size());
        return response;
    }
One approach you could pick here is to design your data stores in Storage interfaces in an increasing fashion.



private List&lt;Cab&gt; getCabs(Key key) {
    List&lt;Cab&gt; cabsByKey = this.cache.stream().filter(c -&gt; c.equals(key)).anyMatch();
    if (cabsByKey.isEmpty()) {
       cabsByKey = this.higherStorage.getByKey(key);
    }

    return cabsByKey;
}


The idea is to store its higher level cache instance for each data storage and to propagate request up whenever nothing has been found.