简体   繁体   中英

Count each word on a string Java

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. Eg:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM