Multiple Key Cards and Partial Query

I am implementing a map implementation with multiple keys. I know Apache Commons , but it doesn't satisfy me.

I want to be able to pass one key and get all records containing the passed key, for example.

MultiKeyMap mkm = new MultiKeyMap();
mkm.put("key1", "key2", "key3", "1");
mkm.put("key1", "key22", "key33", "2");
mkm.put("key12", "key22", "key32", "3");

mkm.get("key1");

      

returns null, but in this case I want to get "1" and "2", My own implementation is not an option. I want to use something I can trust.

+3


source to share


3 answers


I think Guava has a table implementation Table<Key1,Key2,Value>

where you can do table.get(key1)

either table.get(key2)

or table.get(key1, key2)

. I think it only supports two keys per table, but not sure. You can take a look at this.



Guava javadoc table

+3


source


I think you can do it with HashMap



HashMap<String, ArrayList<String>> map = new HashMap<>();
    ArrayList<String> ls=new ArrayList<>();
    ArrayList<String> ls2=new ArrayList<>();
    ls.add("key3");
    ls.add("1");
    ls.add("key2");
    ls.add("key22");
    ls.add("key33");
    ls.add("2");

    ls2.add("key22");
    ls2.add("key32");
    ls2.add("3");

    map.put("key1",ls);
    map.put("key12", ls2);

    map.get("key1");

      

+1


source


If you can include a requirement and put the value multiple times, once for each key, then Guava MultiMap is very nice to use:

    Multimap<String, String> map = HashMultimap.create();
    map.put("key1", "1");
    map.put("key2", "1");
    map.put("key3", "1");

    map.put("key1", "2");
    map.put("key22", "2");
    map.put("key33", "2");

    map.put("key12", "3");
    map.put("key22", "3");
    map.put("key32", "3");

    Collection<String> values = map.get("key1");
    System.out.println(values);

      

prints

    [2, 1]

      

0


source







All Articles