Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program to find the most frequent word in a text and print it,
- * as well as how many times it appears in format "word -> count".
- * Consider any non-letter character as a word separator.
- * Ignore the character casing. If several words have the same maximal frequency,
- * print all of them in alphabetical order. */
- import java.util.ArrayList;
- import java.util.Scanner;
- import java.util.TreeMap;
- public class _11_MostFrequentWord {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.println("Enter your text on single line:");
- String inputLine = scan.nextLine().toLowerCase();
- String[] text = inputLine.split("[^a-z]+");
- TreeMap<String, Integer> frequentWords = new TreeMap<>();
- for (String string : text) {
- Integer times = frequentWords.get(string);
- if (times == null) {
- times = 0;
- }
- frequentWords.put(string, times + 1);
- }
- ArrayList<String> mostFrequentWords = new ArrayList<>();
- int maxTimesAppears = 1;
- for (String key : frequentWords.keySet()) {
- if (frequentWords.get(key) > maxTimesAppears) {
- maxTimesAppears = frequentWords.get(key);
- mostFrequentWords = new ArrayList<>();
- mostFrequentWords.add(key);
- } else if (frequentWords.get(key) == maxTimesAppears) {
- mostFrequentWords.add(key);
- }
- }
- for (String word : mostFrequentWords) {
- System.out.println(word + " -> " + frequentWords.get(word)
- + " times");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement