您的位置:首页 > 其它

找出字符串中特定字符出现的次数的实现(分拣思路)

2017-07-04 19:46 561 查看
通过HashMap和Set接口实现

public class Letter {
private String name;
private int count;
public Letter(){

}
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;
}

}


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
* This is a cat and that is a mice and where is the food?
* 统计每个单词出现的次数
* 存储到map中
* Key:String
* value:自定义类型
*
* "分拣"思路
* 第一种:为所有的Key创建容器
*  之后容器中存放对应value
* 第二种:第一次创建容器,并存放值value
*    第二次之后,直接使用容器存放值
* @author Administrator
*
*/
public class Demoo1 {
public static void main(String[] args) {
String s="This is a cat and that is a mice and where is the food";
//分割字符串
String[] strArray=s.split(" ");
//存储到Map中
Map<String,Letter> letters=new HashMap<String,Letter>();
for (String temp : strArray) {
/*
* 1.为所有的Key存放容器
* 之后容器存放对应的value
*/
if(!letters.containsKey(temp)){
letters.put(temp, new Letter());
}

Letter col = letters.get(temp);//直接获取容器
col.setCount(col.getCount()+1);
}
//输出map的值
Set<String> keys=letters.keySet();
for (String key : keys) {
Letter col = letters.get(key);
System.out.println("字母:"+key+",次数:"+col.getCount());
}
}
}


第二种:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
* This is a cat and that is a mice and where is the food?
* 统计每个单词出现的次数
* 存储到map中
* Key:String
* value:自定义类型
*
* "分拣"思路
* 第一种:为所有的Key创建容器
*  之后容器中存放对应value
* 第二种:第一次创建容器,并存放值value
*    第二次之后,直接使用容器存放值
* @author Administrator
*
*/
public class Demoo1 {
public static void main(String[] args) {
String s="This is a cat and that is a mice and where is the food";
String[] strArray=s.split(" ");
Map<String,Letter> letters=new HashMap<String,Letter>();
for(String temp:strArray){
//为所有Key创建容器
Letter col=null;
if(null==(col=letters.get(temp))){
col=new Letter();
col.setCount(1);//第一次值存放容器中
letters.put(temp,col);
}else{
//直接使用容器存放值
col.setCount(col.getCount()+1);
}

}
//输出map的值
Set<String> keys=letters.keySet();
for (String key : keys) {
Letter col = letters.get(key);
System.out.println("字母:"+key+",次数:"+col.getCount());
}
}
}


输出:

字母:the,次数:1
字母:a,次数:2
字母:that,次数:1
字母:and,次数:2
字母:cat,次数:1
字母:This,次数:1
字母:is,次数:3
字母:where,次数:1
字母:mice,次数:1
字母:food,次数:1


总结:多看多理解多写
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hashmap