首页 > 解决方案 > 如何通过 Java 中的 HashMap 提高迭代性能?

问题描述

有人知道如何提高这种方法的性能吗?请注意,this.allActions 是一个带有大约一百万个键的哈希图。

也许有一种更快的方法来遍历我不知道的 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;
    }

标签: javahashmap

解决方案


转换HashMapLinkedHashMap以提高性能,

Get O(1) 的复杂度,包含 O(1) 和 Next O(1)

, 您可以创建自定义 Key 类和更新hashCode()函数

像这样使用它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();
    }
  }

推荐阅读