My Answer:
package testjava; import java.io.bufferedreader;import java.io.file;import java.io.filereader;import java.util.arraylist;import java.util.hashmap;import java.util.iterator;import java.util.map;import java.util.map.entry; public class findmostfrequency { arraylist<string> words = new Arraylist<string> (); hashmap<string, integer> word_frequency = new HashMap<String, Integer> (); hashmap<string, Integer> word_position = new hashmap<string, integer> (); public static void main (String[] args) { // TODO Auto-generated method stub findmostfrequency find = new findmostfrequency (); find.readfile ("D:/test.txt"); HashMap<String, Integer> result = Find.findmostfrequencyword (); system.out.println (Result); } public string replacepunc (STRING&NBSP;STR) { return str.replaceall ("[\\pP]", " "); } public string[] convertstr (STRING&NBSP;STR) { return str.split ("\\s+"); } public void readfile (String filepath) { file file = new file (FilePath); if (FILe.exists ()) { try { BufferedReader Br = new bufferedreader (New filereader (file)); String line = null; int linenum=1; while (line = br.readline ()) != null) { string[] wordlist = this.convertstr (This.replacepunc (line)); int count = 0; String word = null; for (int i = 0; i < wordlist.length; i++) { word=wordList[i]; if (Words.contains (word)) { count = word_frequency.get (word) + 1; word_frequency.put (Word, count); } else { words.add (word); word_frequency.put (word, 1); this.word_position.put (Word, linenum); } } linenum+ +; } br.close (); } catch (exception e) { // todo Auto-generated catch block e.printstacktrace (); } } else { system.out.println ("This file doesn ' t exist!"); } } public hashmap<string,integer> findmostfrequencyword () { int max=0; hashmap<string,integer> res = new HashMap<String,Integer> ( iterator); <entry<string, integer>> it=this.word_frequency.entryset (). Iterator (); while (It.hasnext ()) { map.entry<string, integer> entry=it.next (); if (ENTRY.GEtvalue () >max) { res = new HashMap<String,Integer> (); res.put (Entry.getkey (), This.word_position.get ( Entry.getkey ())); max=entry.getvalue (); } else if (Entry.getValue () ==max) { res.put (Entry.getKey (), This.word_position.get (Entry.getkey ())); } else{ continue; } } return res; }}
JAVA Interview question: Find most frequency word in a paragraph