Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.Paths;
  6. import java.util.*;
  7. import java.util.stream.Collectors;
  8.  
  9. public class Main {
  10.  
  11.     private static int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
  12.         int valCmp = o1.getValue().compareTo(o2.getValue());
  13.         return valCmp == 0 ? o2.getKey().compareTo(o1.getKey()) : valCmp;
  14.     }
  15.  
  16.     public static void main(String[] args) throws IOException {
  17.  
  18.         String text = new String(Files.readAllBytes(Paths.get("text.txt"))).toLowerCase();
  19.         String[] words = text.split("\\W+");
  20.  
  21.         HashMap<String, Integer> topWords = new HashMap<>();
  22.         for(String word : words){
  23.  
  24.             if(topWords.containsKey(word)) {
  25.                 topWords.put(word, topWords.get(word) + 1);
  26.             }
  27.             else {
  28.                 topWords.put(word, 1);
  29.             }
  30.  
  31.         }
  32.  
  33.         List<Map.Entry> topList = topWords.entrySet().stream().sorted(Main::compare).collect(Collectors.toList());
  34.         Collections.reverse(topList);
  35.  
  36.         System.out.println(topList);
  37.  
  38.     }
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement