思路:把字符串转换成数组,遍历数组,用map容器存储
用key做判断,不存在put,存在value+1,并放入容器中,迭代map容器打印结果
package Collections;
import java.util.*;
/**
* "*Constructs a new <tt>HashMap</tt> ⼩滴课堂 with the same mappings as the *
* ⼩滴课堂 specified <tt>Map</tt>. The <tt>HashMap</tt> is created with default
* load factor (0.75) and an initial capacity sufficient to*hold the mappings
* in the specified <tt>Map</tt>."
*/
public class Times {
public static void main(String[] args) {
test1();
}
public static void test1() {
String str = "\"*Constructs a new <tt>HashMap</tt> ⼩滴课堂 with the same mappings as the *\n" +
"⼩滴课堂 specified <tt>Map</tt>. The <tt>HashMap</tt> is created with default\n" +
"load factor (0.75) and an initial capacity sufficient to*hold the mappings\n" +
"in the specified <tt>Map</tt>.\"";
char [] charArr = str.toCharArray();
Map<Character,Integer> charMap = new HashMap<>();
for(char c : charArr){
Integer value = charMap.get(c);
if(charMap.get(c) == null){
charMap.put(c,1);
}else{
value++;
//加完放入容器中
charMap.put(c,value);
}
}
Set<Character> keySet = charMap.keySet();
Iterator<Character>iterator = keySet.iterator();
while(iterator.hasNext()){
Character character=iterator.next();
System.out.println(character+", 个数"+charMap.get(character));
}
}
}