I've seen a lot of nice solutions here about how to work with ArrayList and HashMaps, but the point is I still can't solve my problem.
So, the idea is there are few people that drink beer, wine and cola. So, it looks like that (for example):
Steve wine
Steve cola
Ben cola
Frank wine
Ben cola
Ben cola
Frank wine
In the end I need to count how many glasses of each drink each of them drank. So, the answer should look like that:
Steve wine 1
Steve cola 1
Ben cola 3
Frank wine 2
My idea was to put to create an object Person(String name, String drink). Then I put all the persons to ArrayList. After that I have created HashMap and wanted to add there a new Person if key doesn't exist, and to increment to 1 if key already exists.
Map<Person, Integer> map = new HashMap<Person, Integer>();
for (Person p : persons)
{
if (map.containsKey(p)) {
map.put(p, map.get(p)+1);
} else {
map.put(p,1);
}
}
It doesn't work. It just returns me the result like this:
Steve wine 1
Steve cola 1
Ben cola 1
Frank wine 1
Ben cola 1
Ben cola 1
Frank wine 1
So, as I understand that should be some other trick here. Maybe you could also tell any other ideas of how to count the glasses of the drinks instead of using HashMap? Many thanks!