1

i need to make a program which reads multiple lines from stdin count the words and then print the words with the number of ocurrence but if two or more words have the same number i have to sort them alphabetically. E.g:

hello world
good morning
hello

The output should be:

hello: 2
good: 1
morning: 1
world: 1

I want to know which is the best way to do this, is hashmap the best way?

  • HashMap is a good way to count the number of occurences. Then you need to get a keyset out of the hashmap and order it alphabetically. – MaxG Feb 25 '16 at 11:31
  • A map is certainly a good place to start. https://stackoverflow.com/questions/21974361/what-java-collection-should-i-use – Tim B Feb 25 '16 at 11:31
  • @Bathsheba Although actually TreeMap doesn't really work as he needs to sort by count then key – Tim B Feb 25 '16 at 11:33

1 Answers1

2

This is actually a more interesting question than it looks like on the surface.

Basically a HashMap<String, Integer> is a good choice, build up a Map with all the words to their count.

You then want to get the entrySet() out of that map and drop the entrySet() from the map into a new ArrayList<Entry<String, Integer>>. You can then use Collections.sort to sort the ArrayList with a custom comparator that first sorts by the value and then by the key.

I'm not going to provide the code for you but if you've any specific questions about any of those steps feel free to ask.

Tim B
  • 40,716
  • 16
  • 83
  • 128