需求结果:
a(3)c(2)g(1)h(5)i(2)j(1)k(1)n(1)o(2)r(1)s(1)t(2)y(1)
package mine;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class MapTest
{
public static void main(String[] args)
{
String str= "anchshayokcjhaioirhtght";
System.out.println(getString(str));
}
public static String getString(String str)
{
char[] ch=str.toCharArray();
TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();
for(char c:ch)
{
Integer value=tm.get(c);
if(value==null)
tm.put(c, 1);
else
tm.put(c,value+1);
}
StringBuilder sb=new StringBuilder();
Set<Character> set=tm.keySet();
Iterator<Character> it=set.iterator();
while(it.hasNext())
{
Character c1=it.next();
sb.append(c1+"("+tm.get(c1)+")");
}
return sb.toString();
}
}
|