繁体   English   中英

使用哪种数据结构(在JAVA中)与3组键以随机顺序使用

[英]What Data Structure to use (in JAVA) with 3 sets of keys in random order

我有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和subtype时:例如type = 1 subtype = 1,则同时返回prodObj1和prodObj2

当给出类型,子类型和id时:例如,type = 1子类型= 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));

我建议使用单个HashMap。 将地图的键设置为三个值的组合。

最简单的将是使用分隔符的String,该分隔符将不会在任何值中使用。 例如,使用Java 8:

String key = String.join(":", type, subType, id) ;
productMap.put(key, product) ;

join方法是空安全的,因此如果缺少这些值就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM