给定一系列字符串:
“chenhao”
“zhangsan”
“zhangsan”
“chenhao”
“lisi”
“wangwu”
“zhaoliu”
“xiaoqiang”
“haha”
打印输出各个字符串出现的次数(使用HashMap实现,键保存字符串,值保存保存出现的次数)
package com.Work7;import org.junit.Test;import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;/*** @Author: 廾匸* @Date: 2020/11/22 23:06* @Description:* @version: 1.01*/
public class Count {
@Testpublic void test(){
String [] str = {
"chenhao","zhangsan","zhangsan","chenhao","lisi","wangwu","zhaoliu","xiaoqiang","haha"};HashMap<String,Integer> hashMap = new HashMap<>();for (int i = 0; i < str.length; i++) {
//将值作为键String key = str[i];// 通过建获取值Integer integer = hashMap.get(key);if(integer==null){
hashMap.put(key,1);}else{
hashMap.put(key,integer+1);}}Count.ToString(hashMap);}// 自写toString 方法private static void ToString(HashMap<String,Integer> hashMap){
Set<String> strings = hashMap.keySet();Iterator<String> iterator = strings.iterator();while(iterator.hasNext()){
String next = iterator.next();System.out.println(next + "出现次数:" + hashMap.get(next));}}
}