Java Program to find each word count in a text file
Example:
Input: Beingcodeexpert is codnig expert side for student. The Beingcodeexpert provide end to end solution of any problem.
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.forEach((k, v) -> System.out.println(k + " " + v));}}
Output
Beingcodeexpert 2end 2expert 1side 1student. 1problem. 1for 1is 1any 1codnig 1The 1provide 1solution 1of 1to 1
No comments:
Post a Comment