Search code examples
javamultikey

Used Multikey(1,2,3) to store entries in Map. Now only have (1) . Can I retrieve all the entries that have (1) in the Multikeys?


I've inserted values into a Map using Multikey with 3 params. Now I would like to retrieve all the entries that have a specific key in their Multikey -and I've no idea as to values of the other 2 ..

map.put(new MultiKey(valueA,valueB,valueC), value);

Now only have valueA , I need to retrieve value

If clarification is required, please ask and I'll elaborate rather than voting to close.. Thanks :)

..


Solution

  • Something as simple as

    static <V> List<V> getValues(Map<MultiKey, V> map, Object key1) {
      List<V> values = new ArrayList<>();
      for (Map.Entry<MultiKey, V> entry : map.entrySet()) {
        MultiKey key = entry.getKey();
        if (key.getKey(0).equals(key1)) {
          values.add(entry.getValue());
        }
      }
      return values;
    }
    

    could work just fine. Extending that to use more than one (key1, key2, ...) is left as an exercise to the reader.