- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Scanner;
- import java.util.Set;
- import java.util.TreeMap;
- public class StringMapDemo {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String string = scanner.next();
- Map<Character, Integer> map = new TreeMap<Character, Integer>();
- for (int i = 0; i < string.length(); i++) {
- char c = string.charAt(i);
- Integer account = map.get(c);
- if(account == null){
- account = 1;
- }
- else {
- account++;
- }
- map.put(c, account);
- }
- Set<Map.Entry<Character, Integer>> set = map.entrySet(); //entrySet()方法得到映射的Set
- Iterator<Map.Entry<Character, Integer>> iterator = set.iterator(); //迭代器访问
- while (iterator.hasNext()) {
- Map.Entry<Character, Integer> entry = iterator.next();
- System.out.println(entry.getKey() + " : " + entry.getValue());
-
- }
- }
- }
复制代码 楼主,我昨晚刚好做了个.你参考下.功能实现了.不过没有用你的代码 |