Skip to content

Instantly share code, notes, and snippets.

@vladholubiev
Created February 15, 2015 22:25
Show Gist options
  • Select an option

  • Save vladholubiev/c6c5bf68d28d06dda61f to your computer and use it in GitHub Desktop.

Select an option

Save vladholubiev/c6c5bf68d28d06dda61f to your computer and use it in GitHub Desktop.
10 lines - write to file most frequent words from .txt
public static void printMostFrequentWords() throws Exception {
PrintWriter fileWriter = new PrintWriter("output.txt");
List<String> words = Arrays.asList(new String(Files.readAllBytes(Paths.get("input.txt"))).split("\\s+"));
words.stream().distinct()
.map((word) -> String.join("", Arrays.asList(word.split("")).stream()
.filter((character) -> Character.isLetter(character.charAt(0)))
.collect(Collectors.toList())))
.map((word) -> new AbstractMap.SimpleEntry<>(word, Collections.frequency(words, word)))
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.forEach((entry) -> fileWriter.println(entry.getValue() + " - " + entry.getKey()));
fileWriter.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment