Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any better solution than three nested Maps that preserves the same functionality?

Here is the situation

private Map<String, Map<String, Map<String, String>>> properties;

And I want to have access to all levels - get Map<String, Map<String, String>>, Map<String, String> or simply just String from the inner map.

Can this be done in a better way to avoid this nested structure? Creating a wrapper which would hide the implementation and provide simple methods is the obvious solution but it just hides the main problem.

like image 638
user219882 Avatar asked Aug 08 '26 14:08

user219882


1 Answers

I like the Key approach.

public class Key {

   private String keyA;
   private String keyB;
   private String keyC;

   public Key(String a, String b, String c) {
      keyA = "".equals(a) ? null : a;
      keyB = "".equals(b) ? null : b;
      keyC = "".equals(c) ? null : c;
   }

   public String getKey(){
      return keyA + keyB + keyC;
   }

   // equals() can be implemented using getKey()
}

And then:

Map<Key, String> map = new HashMap<Key, String>();
map.put(new Key("a", "",""), "only one key");
map.put(new Key("a", "b", "c"), "all keys");

Do notice that you'll only need one map, and can still get an object with only keyA since it will have a different key value.

Of course, if you want to store multiple objects with the same index (or recover multiple objects that start with the same key beginning, as in recover Key("a", "a", "a") and Key("a", "a", "b) when searching for Key("a", "a", "") it will not work. But then, you should not be using a Map anyway, and should probably get a proper database.

like image 128
Marcelo Avatar answered Aug 11 '26 08:08

Marcelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!