Created
February 25, 2021 09:18
-
-
Save ram0973/d9e8b60ed0e7874e638ce9d04a41ff8d to your computer and use it in GitHub Desktop.
Java count most 10 frequent words in text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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