计算文本文件使用地图中的出现次数
下面的代码将计算每个角色的出现次数。 如果我在文本文件输出中有abc将是1 b 1 c 1.我在许多网站中读到for循环将花费大量时间并且最好使用哈希映射实现相同。 你们任何人都可以帮助我如何转换这个实现哈希映射的程序吗?
import java.io.*; class Count_Char { public static void main(String[] args) { try { FileInputStream file = new FileInputStream("D:\\trial.txt"); DataInputStream dis = new DataInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(dis)); String Contents=""; String str=""; while ((Contents = br.readLine()) != null) { str+=Contents; } char[]char_array =str.toCharArray(); for(int count =0;count<char_array.length;count++){ char ch= char_array[count]; int counter=0; for ( int i=0; i=0) { if(ch==char_array[j]) flag=true; j--; } if(!flag){ System.out.println(ch+" "+counter); } } }catch(IOException e1){ System.out.println(e1); } } }
快速伪代码。 基本上,这里的技巧是将字符保存为Map中的键,值是该字符(键/值对)的出现次数。
//declare a map to hold your characters and their counters Map charCounter = new HashMap(); //the following if else logic goes when you are looping through your tokens if(charCounter.containsKey()){ charCounter.put( ,charCounter.get( )+1); }else{ charCounter.put( ,1); }
完成遍历后,您可以通过这种方式打印地图。
for(String key : charCounter.keySet()) { System.out.println(key+" "+charCounter.get(key)); }
FileInputStream file = new FileInputStream(“”); DataInputStream dis = new DataInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String temp=""; Map charCounter = new HashMap(); while ((temp=br.readLine()) != null) { String[] spliter= temp.split(""); for(String temp1:spliter) if(charCounter.containsKey(temp1)){ charCounter.put(temp1,charCounter.get(temp1)+1); }else{ charCounter.put(temp1,1); } } System.out.println(charCounter);
建立在逻辑酷豆上给了hav写它..希望这会有所帮助……我已经测试了这个..