Java:如何为HashMap使用一对键

0 java sql hashmap map

从sql数据库,我正在阅读一个包含2个字段的表:appName,user.所以我可能会看到:

+-------------+
| appA | John |
+-------------+
| appB | Mary |
+-------------+
| appC | Tom  |
+-------------+
| appA | John |
+-------------+
| appA | Mary |
+-------------+
Run Code Online (Sandbox Code Playgroud)

这些记录中的每一个都作为AppClass的对象存储在appName和user中.现在,我想列出不同用户运行应用程序的次数.所以:

+-----------------+
| appA | John | 2 |
+-----------------+
| appA | Mary | 1 | 
+-----------------+
| appB | Mary | 1 |  
+-----------------+
| appC | Tom  | 1 | 
+-----------------+
Run Code Online (Sandbox Code Playgroud)

是否可以使用带有2个键的HashMap进行计数?

Mar*_*elo 5

是的,可以创建一个AppUser包含appName和用户的类.覆盖hashCode()equals()为您的AppUser班级.

然后你可以使用:

Map<AppUser, Integer> map;
Run Code Online (Sandbox Code Playgroud)


Mik*_*uel 5

是.创建一个实现hashCode()equals()正确实现的对,并将其用作密钥类型.如果您正在使用像apache commons这样的库,那么您可以在那里找到一对或者元组类,但是否则以下内容将起作用.

尽管如此,不要过度使用通用对.定义一个关键类来处理集合中的一对项之间的关系是很好的,但是很多人对在Java中广泛使用对类有原则性的反对意见.

public final class PairKey<A, B> {
  public final A a;
  public final B b;

  private PairKey(A a, B b) { this.a = a; this.b = b; }

  public static <A, B> PairKey<A, B> make(A a, B b) { return new PairKey<A, B>(a, b); }

  public int hashCode() {
    return (a != null ? a.hashCode() : 0) + 31 * (b != null ? b.hashCode() : 0);
  }

  public boolean equals(Object o) {
    if (o == null || o.getClass() != this.getClass()) { return false; }
    PairKey that = (PairKey) o;
    return (a == null ? that.a == null : a.equals(that.a))
        && (b == null ? that.b == null : b.equals(that.b));
  }
}
Run Code Online (Sandbox Code Playgroud)

然后将a和b的条目放入地图中,就这样做

myMap.put(new PairKey(a, b), value)
Run Code Online (Sandbox Code Playgroud)