Java: how to use a key pair for HashMap

From the sql database I am reading a table with two fields: appName, user. Therefore, I can see:

+-------------+ | appA | John | +-------------+ | appB | Mary | +-------------+ | appC | Tom | +-------------+ | appA | John | +-------------+ | appA | Mary | +-------------+ 

Each of these entries is stored as an AppClass object with the application name and user. Now I want to indicate how many times applications have been launched by different users. So:

 +-----------------+ | appA | John | 2 | +-----------------+ | appA | Mary | 1 | +-----------------+ | appB | Mary | 1 | +-----------------+ | appC | Tom | 1 | +-----------------+ 

Is it possible to count using a HashMap with two keys?

0
source share
5 answers

Yes, you may have a structure such as:

 Map<String, Map<String, Integer>> ^ ^ ^ appName user count 

But it would be much simpler if you just retrieved the aggregated data directly from the database:

 SELECT appName, user, COUNT(*) FROM table GROUP BY appName, user; 
+2
source

Yes, maybe create an AppUser class that includes the application and user name. Override hashCode() and equals() for your AppUser class.

Then you can use:

 Map<AppUser, Integer> map; 
+5
source

Yes. Create a pair that correctly implements hashCode() and equals() and uses this as the key type. If you use a library like apache commons, you can probably find a pair or tuple there, but otherwise it will work.

Do not overdo it from common pairs. It's good to define a key class for handling the relationship between a pair of elements in a collection, but many people have fundamental objections to the widespread use of paired classes in 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)); } } 

and then put the entry for a and b on the card, just do

 myMap.put(new PairKey(a, b), value) 
+5
source

What about

 Map<String, Integer> appUserToCountMap 

use appA:John as a key e.g.

+3
source

You may also consider using Commons Collection Bags. See Bag.getCount(key)

0
source

All Articles