title: Efficient way of mimicking hibernate criteria on cached map
body: <p>I have just wrote a code to cach a table in the memory (simple java hashmap). Now one of the code that i am trying to replace is the find the objects based on criteria. it receives multiple field parameters and if those fields are not empty and not null, they were being added as part of hibernate query criteria. </p>
  
  <p>To replace this, what i am thinking to do is</p>
  
  <ol>
  <li>For each <em>valid param (not null and no empty)</em> I will create a HashSet which will satisfy this criteria.</li>
  <li>Once i am done making hashsets for all valid criteria, I will call <code>Set.retainAll(second_set)</code> on all sets. So that at the end, I will have only that set which is intersection of all valid criteria. </li>
  </ol>
  
  <p>Does it sound like the best approach or is there any better way to implement this ?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Though, My original post is still valid and I am looking for that answer. I ended up implementing it in the following way. The reason is that it was kind a cumbersome with sets since after creating all sets, I had to first figure out which set is non empty so that the retainAll could be called. it was resulting in lots of if-else statements. My current implementation is like this</p>
  
  <pre><code>private List&lt;MyObj&gt; getCachedObjs(Long criteria1, String criteria2, String criteria3) {
      List&lt;MyObj&gt; results = new ArrayList&lt;&gt;();
      int totalActiveFilters = 0;
  
      if (criteria1 != null){
          totalActiveFilters++;
      }
  
      if (!StringUtil.isBlank(criteria2)){
          totalActiveFilters++;
      }
  
      if (!StringUtil.isBlank(criteria3)){
          totalActiveFilters++;
      }
  
      for (Map.Entry&lt;Long, MyObj&gt; objEntry : objCache.entrySet()){
          MyObj obj = objEntry.getValue();
  
          int matchedFilters = 0;
  
          if (criteria1 != null) {
              if (obj.getCriteria1().equals(criteria1)) {
                  matchedFilters++;
              }
          }
  
          if (!StringUtil.isBlank(criteria2)){
              if (obj.getCriteria2().equals(criteria2)){
                  matchedFilters++;
              }
          }
  
          if (!StringUtil.isBlank(criteria3)){
              if (game.getCriteria3().equals(criteria3)){
                  matchedFilters++;
              }
          }
  
          if (matchedFilters == totalActiveFilters){
              results.add(obj);
          }
      }
      return results;
  }
  </code></pre>