黑马程序员技术交流社区
标题:
关于字符串中出现字符的次数,并按次数排序的问题
[打印本页]
作者:
陈嘉宾
时间:
2012-6-20 00:12
标题:
关于字符串中出现字符的次数,并按次数排序的问题
本帖最后由 陈嘉宾 于 2012-6-20 09:43 编辑
用什么方法才能让value具有比较值大小的方法呢?迭代出来就不知道该用什么方法比较了,想了一晚上好头疼。。。迫不得已清高手帮忙看下。怎么调用比较方法呢?
package cn.itcast.day1;
import java.util.*;
class xp
{
public static void main(String[] args)
{
charCount("abadcdffbaeba");
}
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);
}
}
Set<Character> keySet=tm.keySet();
Iterator<Character>it=keySet.iterator();
while(it.hasNext())
{
Character key=it.next();
Integer value=tm.get(key);
System.out.println(key+"::::"+value);
}
System.out.println(tm);
return null;
}
}
作者:
黑马—陈磊
时间:
2012-6-20 00:55
public static void main(String[] args) {
charCount("abadcdffbaeba");
}
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);
}
}
Set<Character> keySet = tm.keySet();
Iterator<Character> it = keySet.iterator();
int i = 0;
while (it.hasNext()) {
Character key = it.next();
Integer value = tm.get(key);
System.out.println(key + "::::" + value);
}
//把TreeMap对象的entrySet()做成List,然后用Collections类的sort方法排序的,
//而且要用带比较器参数的那个sort,并且比较器要重写compare方法,实现value的比较
List arrayList = new ArrayList(tm.entrySet());
Collections.sort(arrayList, new Comparator() {
public int compare(Object o1, Object o2) {
Map.Entry obj1 = (Map.Entry) o1;
Map.Entry obj2 = (Map.Entry) o2;
return ((Integer) obj2.getValue()).compareTo((Integer) obj1
.getValue());
}
});
System.out.println(arrayList);
return null;
}
作者:
陈嘉宾
时间:
2012-6-20 09:41
恩这个方法我想过。但是却调用方法这块没想明白谢谢你
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2