效果如下:
package cn.edu.nuc.map;
import java.util.HashMap;
import java.util.Map;
public class Test2 {
/**
* 统计字符串中字符出现的次数
* 1.对字符串进行切割
* 2.遍历字符串
* 3.创建map对象,通过字符查看map中是否含有该字符
* 若有该字符,value++;否则,添加该字符,设置value为1
* 4.遍历map 查看统计结果
* @param args
*/
public static void main(String[] args) {
String str="hello tom hello jerry hello tom hello jiji hello tom";
String[] strings = str.split("\\s");
/**
* 方法一 用getOrDefault来设置map
*/
Map<String,Integer> map2 = new HashMap();
for (String string : strings) {
Integer integer = map2.getOrDefault(string, 0);
integer++;
map2.put(string, integer);
}
for (String string : map2.keySet()) {
System.out.println(string+" "+map2.get(string));
}
System.out.println("------------------------------------------");
/**
* 方法二 if-else创建
*/
Map<String,Integer> map1 = new HashMap();
for (String string : strings) {
Integer integer = map1.get(string);
if(integer==null)
map1.put(string,1);
else {
integer=integer+1;
map1.put(string,integer);
}
}
for (String string : map1.keySet()) {
System.out.println(string+" "+map1.get(string));
}
}
}
二、从一个文件中输入数据,进行分割后,再输出到另一个文件中
public class Test5{
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("d:/a/hello.txt");
FileOutputStream fos = new FileOutputStream("d:/a/result.txt");
//创建管道 用来接收数据
StringBuffer strb = new StringBuffer();
int len = 0;
while((len=fis.read())!=-1) {
strb.append(new String(new byte[] {(byte)len}));
}
System.out.println(strb);
//将接收到的数据转换成字符串,分割 并存到map中
String str = strb.toString();
String[] split = str.split("\\s");
Map<String,Integer> map = new HashMap<>();
for (String string : split) {
if(!map.containsKey(string)) {
map.put(string, 1);
}else {
int value = map.get(string);
map.put(string, value+1);
}
}
//往文件里写入
String s ="";
for (String string : map.keySet()) {
System.out.println(string+":"+map.get(string));
s = s+string +":"+map.get(string)+"; ";
}
System.out.println(s);
//将String转换成字节进行写入
byte[] byte1 = s.getBytes();
fos.write(byte1);
fos.close();
fis.close();
}
}