Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Map;
- import java.util.Scanner;
- import java.util.TreeMap;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class _11_MostFrequentWord {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- String input = sc.nextLine().toLowerCase();
- Pattern regex = Pattern.compile("\\w+");
- Matcher matcher = regex.matcher(input);
- ArrayList<String> allWords = new ArrayList<>();
- while(matcher.find()){ //Put all words in ArrayList
- allWords.add(matcher.group());
- }
- Map<String, Integer> result = new TreeMap<>();
- for(String word : allWords){ //Make counter for every word
- Integer count = result.get(word);
- if(count == null){
- count = 0;
- }
- result.put(word, count + 1);
- }
- int highestCount = 0; //Find the highest count of a word
- for(String word : result.keySet()){
- int count = result.get(word);
- if(count > highestCount){
- highestCount = count;
- }
- }
- for(String word : result.keySet()){ //Print the word/s with highest count
- int count = result.get(word);
- if(count == highestCount){
- System.out.printf("%s -> %d times \n", word, count);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment