这里需要提到分拣存储,用一个发快递的示例来解释,在快递公司收到快递的时候,他会对快递进行分类,从各个地方来的快递就放在同一个袋子中,比如从北京来的快递,看看有没有北京这个袋子,如果有就放进去,没有就新建一个袋子,然后放进去。
回到正题,统计句子中单词出现的次数,假设这个句子是 this is a cat and that is a mice and where is the food,当然这个句子可以是给定的,也可以是从控制台输入的。
那么第一步,我们需要把句子按空格分隔为单词,并放在数组中
第二步,分拣存储,也就是这里用到了HashMap
第三步,按要求查看单词出现的次数
HashMap是键值对存储,设置HashMap的泛型为<String,Integer>,key值为分割出来的单词,value为出现数, 一个key对应一个value,我们传统的添加都是,当key值相同时,覆盖掉value的值,保证key和value的一对一关系,但是这里并不是我们想要的结果,我们需要当key值一样时,value值加一,value表明key在句子中的出现次数
代码实现:
public static void main(String[] args) {
//1.按空格分割字符串
String[] arr="this is a cat and that is a mice and where is the food".split(" ");
//2.分拣存储
Map<String,Integer> map=new HashMap<String,Integer>();
for(String key:arr){
if(!map.containsKey(key)){
map.put(key, 1);
}else{
map.put(key, map.get(key)+1);
}
}
//3.用迭代器查看单词出现的次数
Set<String> keySet=map.keySet();
Iterator<String> it=keySet.iterator();
while(it.hasNext()){
String key=it.next();
Integer value=map.get(key);
System.out.println(key+"----"+value);
}
}mice---1
that---1
cat---1
is---3
food---1
a---2
the---1
where---1
this---1
and---2上面的代码中我们直接用了Integer来计数,我们也可以设计一个javabean类
javabean就是一种定义类的规范,可以用来存储数据,说白了也就是成员变量私有,添加setter和getter方法的类
定义一个Letter类,有两个属性,存放单词,和出现次数
public class Letter {
private String name;
private int count;
public Letter() {
// TODO Auto-generated constructor stub
}
public Letter(String name) {
super();
this.name = name;
}
public Letter(String name, int count) {
super();
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}在定义好Letter类以后,同样的利用HashMap进行分拣存储
public static void main(String[] args) {
//1.按空格分割字符串
String[] arr="this is a cat and that is a mice and where is the food".split(" ");
//2.分拣存储
Map<String,Letter> map=new HashMap<String,Letter>();
for(String key:arr){
if(!map.containsKey(key)){
map.put(key, new Letter(key));
}
//获取袋子
Letter value=map.get(key);
value.setCount(value.getCount()+1);
}
//3.查看每个单词出现的次数
for(String key:map.keySet()){
Letter value=map.get(key);
System.out.println(key+"---"+value.getCount());
}
}输出结果一致
版权声明:本文为Bazingaea原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。