Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.util.*;
- import java.util.stream.Collectors;
- public class Main {
- private static int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
- int valCmp = o1.getValue().compareTo(o2.getValue());
- return valCmp == 0 ? o2.getKey().compareTo(o1.getKey()) : valCmp;
- }
- public static void main(String[] args) throws IOException {
- String text = new String(Files.readAllBytes(Paths.get("text.txt"))).toLowerCase();
- String[] words = text.split("\\W+");
- HashMap<String, Integer> topWords = new HashMap<>();
- for(String word : words){
- if(topWords.containsKey(word)) {
- topWords.put(word, topWords.get(word) + 1);
- }
- else {
- topWords.put(word, 1);
- }
- }
- List<Map.Entry> topList = topWords.entrySet().stream().sorted(Main::compare).collect(Collectors.toList());
- Collections.reverse(topList);
- System.out.println(topList);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement