我有3组键:一个是类型,另一个是子类型,最后一个是ID,值是ProductObj。最初,我想将ProductObj存储在HashMap的HashMap的HashMap中(HashMap<type, HashMap<subtype, HashMap<ID, prodObj>>>),以便进行更快的搜索(希望将其设计为Cache而不是从数据库中不断检索)。 [注意:productObj的数量是固定的]但是,我了解到50%的时间中,我可能只会获得ID而不是类型/子类型,另外50%是类型/子类型,但没有ID。什么样的数据结构才能满足此目的?

我想到了HashMap<type, HashMap<subtype, HashMap<ID, uuid>>>和另一个HashMap<uuid, prodObj>,但是我希望在数据结构方面找到更好的解决方案。提前致谢!

[附加信息]

这就是希望存储的内容{type = 1 subtype = 1 id = 1 = prodObj1,type = 1 subtype = 1 id = 2 = prodObj2,...}

当提供ID时:例如id = 1,然后返回prodObj1

输入类型时:例如type = 1,同时返回prodObj1和prodObj2

当给出类型和子类型时:例如type = 1子类型= 1,同时返回prodObj1和prodObj2

输入类型时,会给出子类型和ID:例如type = 1 subtype = 1 id = 1,则返回prodObj1

我希望利用像HashMap这样的数据结构来基于键值进行更快的搜索,因为我将访问缓存并经常更改prodObj状态。

最佳答案

为什么要使用嵌套地图?

如果您不操作地图中的大量值,则可以将定义复合键(类型,子类型和id)的自定义类用作键。

通过这种方式,您可以在获取或插入该复合键的实例时,将其传递给地图。

public class ProductKey{

  private Long id;
  private string type;
  private string subType;

  private ProductKey(){
  }

  public static ProductKey ofWithId(Long id){
    ProductKey productKey = new ProductKey();
    productKey.id = id;
    return productKey;
  }
   ...
  // other factory methods
   ...
  // equals and hashcode overriden of course
}


您可以通过以下方式实例化并填充地图:

Map<ProductKey, ProductObj> map = new HashMap<>();
map.put(ProductKey.ofWithId(1), myProductObj);
map.put(ProductKey.ofWithTypeAndSubType("type", "subtype"), anotherProductObj);
 ...


并以这种方式检索元素:

 ProductObj retrievedObj = map.get(ProductKey.ofWithId(1));

10-08 07:06
查看更多