来说一下我自己定义的比较TreeMap<key,value>中value的方法
在定义TreeMap的类中自定义一个内部类,封装key value值 实现comparator
覆盖compareTo方法 就像姓名-----年龄 一样封装
class Demo{
public void treemapdemo( ){
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
.............
//遍历集合将遍历的key value 封装对象加入到TreeSet集合中
Set<ToSort> sort = new TreeSet<ToSort>();
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();
sort.add(new ToSort(ch,value));//使用内部类
}
for (ToSort s: sort)
{
sb.append(s);
}
String str1 = sb.toString();
str = (String)str1.subSequence(0, str1.length()-2);
System.out.println("排序后:"+str);
}
private class ToSort implements Comparable<ToSort>{
private Character key;
private Integer value;
ToSort(Character key,Integer value)
{
this.key = key;
this.value = value;
}
public Character getKey() {
return key;
}
public Integer getValue() {
return value;
}
public int compareTo(ToSort s)
{
int num = new Integer(this.value).compareTo(new Integer(s.value));
if (num==0)
return this.key.compareTo(s.key);
return num;
}
public String toString()
{
return key+" : "+value+", ";
}
}
}
}
|