Java 用hashmap统计词频

来源:互联网 发布:java关键字 false 编辑:程序博客网 时间:2024/05/21 17:02

C:\\Temp\\1\\a.txt   内容:
1,a,282,b,353,c,284,d,355,e,286,a,287,b,358,c,289,a,28


public class FileTest{    static File filea = new File("C:\\Temp\\1\\a.txt");    static HashMap<String,Integer> hashmap = new HashMap<String,Integer>();    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<String, Integer> 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的话,可以直接用






0 0
原创粉丝点击