使用Map集合计算字符串单词的个数

package kernel.array.com;


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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值