java - How to count the number of unique values in HashMap? -


i've seen lot of nice solutions here how work arraylist , hashmaps, point still can't solve problem.

so, idea there few people drink beer, wine , cola. so, looks (for example):

steve wine steve cola ben cola frank wine ben cola ben cola frank wine 

in end need count how many glasses of each drink each of them drank. so, answer should that:

steve wine 1 steve cola 1 ben cola 3 frank wine 2 

my idea put create object person(string name, string drink). put persons arraylist. after have created hashmap , wanted add there new person if key doesn't exist, , increment 1 if key exists.

    map<person, integer> map = new hashmap<person, integer>();      (person p : persons)     {         if (map.containskey(p)) {             map.put(p, map.get(p)+1);         } else {             map.put(p,1);         }    } 

it doesn't work. returns me result this:

 steve wine 1  steve cola 1  ben cola 1  frank wine 1  ben cola 1  ben cola 1  frank wine 1 

so, understand should other trick here. maybe tell other ideas of how count glasses of drinks instead of using hashmap? many thanks!

if can use java 8 streams here 1 clever solution :

    list<person> people = arrays.aslist(new person("steve", "wine"), new person("steve", "cola"),             new person("ben", "cola"), new person("ben", "cola"), new person("steve", "wine"),             new person("steve", "wine"));      map<person, long> map = people.stream()             .collect(collectors.groupingby(function.identity(), collectors.counting())); 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -