Java Program to find the most repeated word in a text file
Example:
Input: Beingcodeexpert is codnig expert side for student. The Beingcodeexpert provide end to end solution of any problem.
Output: Most repeatable word is Beingcodeexpert times 2
Approach
Java
import java.io.BufferedReader;import java.io.FileReader;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.stream.Collectors;public class WordCountInFile {public static void main(String[] args) throws Exception {String line;// file open using FileReaderFileReader file = new FileReader("D://data.txt");BufferedReader br = new BufferedReader(file);HashMap<String, Integer> map = new HashMap<String, Integer>();// Iterate file till end of linewhile ((line = br.readLine()) != null) {String words[] = line.split(" ");for (String string : words) {map.put(string, map.getOrDefault(string, 0) + 1);}}br.close();// sort the map using valuemap = map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (o2V, o1V) -> o2V, LinkedHashMap::new));Map.Entry<String, Integer> entry =map.entrySet().iterator().next();String key = entry.getKey();Integer value = entry.getValue();System.out.println("Most repeatable word is " + key + " times " + value);}}
No comments:
Post a Comment