/****************************************************************************** * This program reads characters from STDIN and then computes a * word frequency table. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.pureprogrammer.Utils; public class FrequencyTableWords { public static void main(String[] args) { int totalCount = 0; Map countTable = new HashMap<>(); String line; while ((line = Utils.getline()) != null) { final List words = Arrays.asList(Pattern.compile("\\W+").split(line)); for (String word : words) { final String lc = word.toLowerCase(); if (Utils.cpLength(lc) > 0) { if (!countTable.containsKey(lc)) { countTable.put(lc, 1); } else { countTable.put(lc, countTable{lc} + 1); } ++totalCount; } } } System.out.println("Word\tCount\tFreq"); final List sortedKeys = Utils.sort(List.copyOf(countTable.keySet())); for (String x : sortedKeys) { final double FREQ = countTable.get(x) / (double)(totalCount); System.out.println(Utils.format("{0:s}\t{1:d}\t{2:.6f}", x, countTable.get(x), FREQ)); } } }