简体   繁体   English

如何通过 Java 中的 HashMap 提高迭代性能?

[英]How to improve performance of iteration through a HashMap in Java?

Does anybody have any idea about how I could improve the performance of this method?有人知道如何提高这种方法的性能吗? Note that this.allActions is a hashmap with around half a million keys.请注意,this.allActions 是一个 hashmap,具有大约 50 万个密钥。

Maybe there is a faster way of iterating through a HashMap that I don't know.也许有一种更快的方法来遍历我不知道的 HashMap。

public String get_random_legal_action(String stateJSON) {

        Collections.shuffle(this.allActionsKeys);

        boolean legal;

        HashMap<String, Integer> state = new Gson().fromJson(stateJSON, this.stateType);

        for (String action : this.allActionsKeys) {

            legal = true;

            for (Map.Entry<String, Integer> precondition : this.allActions.get(action).precondition.entrySet()) {
                try {
                    if (!state.get(precondition.getKey()).equals(precondition.getValue())) {
                        legal = false;
                        break;
                    }
                } catch (NullPointerException e) {
                    if (!this.immutableProps.contains(precondition.getKey())) {
                        legal = false;
                        break;
                    }
                }
            }

            if (legal)
                return action;
        }

        return null;
    }

Convert the HashMap to LinkedHashMap to improve the performance,HashMap转换为LinkedHashMap以提高性能,

the complexity of Get O(1), Contains O(1) and Next O(1) Get O(1) 的复杂度,包含 O(1) 和 Next O(1)

, You can create custom Key class and update hashCode() function , 您可以创建自定义密钥 class 并更新hashCode() function

Use it in like LinkedHashMap<Key, Integer>LinkedHashMap<Key, Integer>一样使用它

static class Key {

    private static final int R = 256;
    private static final long Q = longRandomPrime();

    private String k;

    public Key(String k) {
      this.k = k;
    }

    public String key() {
      return k;
    }

    @Override
    public int hashCode() {
      return Long.hashCode(hash());
    }

    @Override
    public boolean equals(Object o) {
      if (this == o)
        return true;
      if (o == null)
        return false;
      if (getClass() != o.getClass())
        return false;
      Key other = (Key) o;
      return k.equals(other.k);
    }

    @Override
    public String toString() {
      return k;
    }

    private long hash() {
      long h = 0;
      for (int j = 0; j < k.length(); j++) {
        h = (R * h + k.charAt(j)) % Q;
      }
      return h;
    }

    private static long longRandomPrime() {
      BigInteger prime = BigInteger.probablePrime(31, new Random());
      return prime.longValue();
    }
  }

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

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