本帖最后由 jadeite 于 2013-9-2 15:50 编辑
Set存储的是单列集合,把上面代码修改为Set<Character> keySet = tm.entrySet();这样才是遍历集合的key值,迭代器那块也这样改
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
class MapTest3 {
public static void main(String[] args) {
String s = CharCount("asdggdasfjklsdad");
sop(s);
}
public static void sop(Object obj) {
System.out.println(obj);
}
public static String CharCount(String str) {
char[] chs = str.toCharArray();
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
for (int x = 0; x < chs.length; x++) {
Integer value = tm.get(chs[x]);
if (value == null) {
tm.put(chs[x], 1);
} else {
value = value + 1;
tm.put(chs[x], value);
}
}
/*
*
* //entrySet()方法。 StringBuilder sb = new StringBuilder();
* Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
* Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
* while(it.hasNext()) { Map.Entry<Character,Integer> me = it.next();
* Character ch = me.getKey(); Integer value = me.getValue();
* sb.append(ch+"("+value+")"); }
*/
// keySet()方法。
StringBuilder sb = new StringBuilder();
Set<Character> keySet = tm.keySet();
Iterator<Character> it = keySet.iterator();
while (it.hasNext()) {
Character ch = it.next();
Integer value = tm.get(ch);
sb.append(ch + "(" + value + ")");
}
return sb.toString();
}
}
|