Which Java Collection class is better to group the list of objects?
I have a list of messages from users like below:
aaa hi
bbb hello
ccc Gm
aaa Can?
CCC yes
ddd No
From this list of message object I want to count and display aaa(2)+bbb(1)+ccc(2)+ddd(1)
. Any code help?
You can use
Map<String, Integer>
where the keys represent the individual strings, and the map value is the counter for each one.So you can do something like:
And then you can iterate the map when done:
and build your result string.
That was like the old-school implementation; if you want to be fancy and surprise your teachers, you can go for the Java8/lambda/stream solution. ( where i wouldn't recommend that unless you really invest the time to completely understand the following solution; as this is untested from my side)
Assuming that you use Java 8, it could be something like this using the Stream API:
Output:
If you want to group your messages by login and have the result as a collection, you can proceed as next:
Putting the pieces together from a couple of the other answers, adapting to your code from the other question and fixing a few trivial errors:
This prints:
You need a MultiSet from guava. That collection type is tailor-made for this kind of task: