Java 用hashmap统计词频

C:\\Temp\\1\\a.txt   内容:
1,a,28
2,b,35
3,c,28
4,d,35
5,e,28
6,a,28
7,b,35
8,c,28
9,a,28


public class FileTest
{
    static File filea = new File("C:\\Temp\\1\\a.txt");

    static HashMap hashmap = new HashMap();
    public static void main(String[] args) throws IOException
    {  
        BufferedReader bra = new BufferedReader(new FileReader(filea));  
        Scanner sa = new Scanner(bra); 
       
        while(sa.hasNextLine()){ 
            String line = sa.nextLine();
            String name = line.split(",")[1];
            
            if (hashmap.containsKey(name))  
               hashmap.put(name, hashmap.get(name) + 1);  
            else
               hashmap.put(name, 1);  
        } 
         
        for (Entry entry : hashmap.entrySet()){
            Object key = entry.getKey();
            Object val = entry.getValue();
            
            System.out.println(key.toString() + " " + val.toString());
            }
        
        
        
}
}
        


打印

d 1
e 1
b 2
c 2
a 3

注意遍历hashmap的遍历:

a. HashMap的循环,如果既需要key也需要value,直接用


b. 如果只是遍历key而无需value的话,可以直接用






你可能感兴趣的:(JAVA,和,C#)