1、问题
- 按字典顺序输出字符串中的各字母及其个数:统计字符串中各个字母的个数,并按字典顺序输出字母及其个数。如输入“aabbccddfhhddd”输出“a2b2c2d5f1h2”。
2、代码
package com.ypj.java;
import java.util.HashMap;
import java.util.Set;
public class HashMapTest {
public HashMap hashMapTest(String[] array){
HashMap<String, Integer> hashmaplist = new HashMap<>();
for(int i=0;i<array.length;i++){
if(!hashmaplist.containsKey(array[i])){
hashmaplist.put(array[i], 1);
}else{
hashmaplist.put(array[i], hashmaplist.get(array[i])+1);
}
}
return hashmaplist;
}
public static void main(String[] args) {
String[] array1 = {"A","B","C","D","A","B","C","D","A","A","B","C","D","A"};
HashMapTest hashMapTest = new HashMapTest();
HashMap hashmap1 = hashMapTest.hashMapTest(array1);
System.out.println(hashmap1);
Set<String> setkey = hashmap1.keySet();
for(String key:setkey){
String m = key;
System.out.print(m+hashmap1.get(m));
}
}
}
3、运行结果