how to find the word with max count in several text files in java?
now i have two arrays. one is string array with words in it. and a count array with corresponding counts in it. below i have printed them together....
ex:
gladiator 8
yamaha 6
gladiator 4
bike 6
brake 4
long 4
time 6
gladiator 35
yamaha 39
bike 17
gladiator 16
ss 19
type 16
yamaha 21
gladiator 15
india 8
yamaha 17
bike 7
gladiator 15
shine 9
yamaha 9
bike 8
gladiator 14
india 8
yamaha 18
bik开发者_JAVA百科e 7
gladiator 9
so now i have first "gladiator" "8" then "gladiator" "4"... so on.... finally i want it as "gladiator" "12"..... like wise
- iterate through list of file names
- open file
- read in line
- split line on space with
String.split(" ")
- convert second element to int with
Integer.parseInt(array[1])
- keep track of highest count, storing
array[0]
when count is higher.
You can parse through the files and store the names and the length in a map.
Map <String,Integer> wordMap = new HashMap<String,Integer>() ;
Then iterate through the map and find the max count. The key corresponding to the max count will be the word.
public class CountWord {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map <String,Integer> wordMap = new HashMap<String,Integer>() ;
int maxCount = 0;
int currentCount = 0;
wordMap.put("Yamaha", new Integer(6));
wordMap.put("Bat", new Integer(3));
wordMap.put("Honda", new Integer(5));
wordMap.put("Book", new Integer(4));
wordMap.put("CutiePie", new Integer(8));
wordMap.put("Project", new Integer(7));
Collection countList = wordMap.values();
Iterator itr = countList.iterator();
while(itr.hasNext()){
currentCount = ((Integer)itr.next()).intValue();
if(maxCount < currentCount){
maxCount = currentCount;
}
}
for (Object key: wordMap.keySet()) {
if(((Integer)wordMap.get(key)).intValue() == maxCount){
System.out.println("The word is : "+key.toString());
}
}
}
}
精彩评论