import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class MapTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//计算一行字符串中每个单词出现的次数
String str ="hello word good moring if you want to learn you must work hard";
String arry[] = str.split(" ");
Map<String,Integer> map1 = new HashMap<String,Integer>();
for(int i = 0;i < arry.length;i++){
Integer freq = map1.get(arry[i]);
map1.put(arry[i], freq == null ?1:freq+1);
}
System.out.println(map1);
//文本中每行中每个单词出现的个数
File f = new File("c:"+File.separator+"test.txt");
try {
BufferedReader buf = new BufferedReader(new FileReader(f));
String str ;
while((str = buf.readLine())!=null){
String arry[] = str.split(" ");
//System.out.println(str);
Map<String,Integer> map1 = new HashMap<String,Integer>();
for(int i = 0;i < arry.length;i++){
Integer freq = map1.get(arry[i]);
map1.put(arry[i], freq == null ?1:freq+1);
}
System.out.println(map1);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random am = new Random();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0;i < 10000;i++){
int r = am.nextInt(20);
Integer freq = map.get(r);
map.put(r, freq == null ?1:freq+1);
}
System.out.println(map);
}
}
运行结果:
{moring=1, learn=1, work=1, want=1, must=1, hello=1, to=1, hard=1, word=1, good=1, if=1, you=2}
java.util.Random@52e922
{0=487, 1=516, 2=498, 3=509, 4=522, 5=510, 6=513, 7=487, 8=476, 9=509, 10=550, 11=467, 12=503, 13=506, 14=489, 15=519, 16=502, 17=519, 18=476, 19=442}