Skip to content

Instantly share code, notes, and snippets.

@ram0973
Created February 25, 2021 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ram0973/d9e8b60ed0e7874e638ce9d04a41ff8d to your computer and use it in GitHub Desktop.
Save ram0973/d9e8b60ed0e7874e638ce9d04a41ff8d to your computer and use it in GitHub Desktop.
Java count most 10 frequent words in text
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String text = br.readLine();
String[] words = text.split("[^a-zA-Z0-9]+");
Arrays.stream(words)
.map(String::toLowerCase)
.collect(Collectors.groupingBy(identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
.limit(10)
.map(Map.Entry::getKey)
.forEach(System.out::println);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment