Frequency counter of words in a String

 import java.util.*;  
 /**  
  * Solution is in java 8  
  * press CTRL-D on new line in Unix or macOS to terminate, CTRL-Z on new line in Windows  
  *  
  * Sample Result:  
  * "C:\Program Files\Java\jdk1.8.0_192\bin\java.exe"  
  * Mightymighty  
  * Hellohello  
  * ^D  
  * Original Text : Mightymighty  
  * Parsed Text :g2h2i2m2t2y2  
  * Original Text : Hellohello  
  * Parsed Text :e2h2l4o2  
  *  
  * Process finished with exit code 0  
  *  
  */  
 public class StringFrequencyCounter {  
   public static void main(String[] args) {  
     StringFrequencyCounter counter = new StringFrequencyCounter();  
     List<String> candidates = counter.validateInputAndGetValue();  
     candidates.forEach(e -> {  
       System.out.format("Original Text : %s%n", e);  
       Map<String, Integer> tokenFrequencyMap = counter.parsedString(e);  
       System.out.print("Parsed Text :");  
       tokenFrequencyMap.forEach((k, v) -> System.out.print(k + "" + v));  
       System.out.println();  
     });  
   }  
   private Map<String, Integer> parsedString(String candidate) {  
     Map<String, Integer> tokenFrequencyMap = new TreeMap<>();  
     for (String token : candidate.split("")) {  
       token = token.toLowerCase();  
       if (tokenFrequencyMap.containsKey(token)) {  
         int value = tokenFrequencyMap.get(token);  
         value++;  
         tokenFrequencyMap.put(token, value);  
       } else {  
         tokenFrequencyMap.put(token, 1);  
       }  
     }  
     return tokenFrequencyMap;  
   }  
   private List<String> validateInputAndGetValue() {  
     List<String> tokens = new ArrayList<>();  
     try {  
       Scanner scanner = new Scanner(System.in);  
       while (scanner.hasNextLine()) {  
         String candidate = scanner.nextLine();  
         tokens.add(candidate);  
       }  
       scanner.close();  
     } catch (final Exception e) {  
       throw new RuntimeException("Not a valid String ", e);  
     }  
     return tokens;  
   }  
 }  

Comments

Popular posts from this blog

FileSystemUtils

Report

AbstractTestNgBaseTest