欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

TreeMap中文排序,TreeMap倒序输出排列

程序员文章站 2022-07-07 19:12:07
1、TreeMap集合倒序排列 import java.util.Comparator; /** * 比较算法的类,比较器 * @author Administrator * */ public class MyCmp implements Comparator { // 实现倒序 @Overrid... ......
1、treemap集合倒序排列
import java.util.comparator;

/**
 * 比较算法的类,比较器
 * @author administrator
 *
 */
public class mycmp implements comparator<object> {

    // 实现倒序
    @override
    public int compare(object o1, object o2) {
        int x =  o2.tostring().compareto(o1.tostring());
        return x;
    }
}
import java.util.iterator;
import java.util.treemap;

public class testmap {

    public static void main(string[] args) {
        treemap<string,string>  map = new treemap<string,string> (new mycmp());
        map.put("10001","张某");
        map.put("10005","孙某");
        map.put("10003","方某");
        map.put("10004","谭某");
        map.put("10002","李某");
        iterator<string> it = map.keyset().iterator();
        while(it.hasnext()){
            string key = it.next();
            system.out.println(key+"="+map.get(key));
        }
    }
}

 TreeMap中文排序,TreeMap倒序输出排列

2、treemap中文排序
import java.text.collationkey;
import java.text.collator;
import java.util.comparator;

/**
 * 处理中文排序
 * @author administrator
 *
 */
public class mycmp1 implements comparator<object> {

    collator collator = collator.getinstance();
    /**
     * 提供以与自然语言无关的方式来处理文本,日期,数字和消息的类和接口
     * 获取当前默认语言环境的collator
     */
    @override
    public int compare(object o1, object o2) {
        // todo auto-generated method stub
        collationkey key1 = collator.getcollationkey(o1.tostring());
        collationkey key2 = collator.getcollationkey(o2.tostring());
        return key1.compareto(key2);
    }
}
import java.util.iterator;
import java.util.map.entry;
import java.util.set;
import java.util.treemap;

public class testmap1 {

    public static void main(string[] args) {
        treemap<string,string> map = new treemap<string,string>(new mycmp1());
        map.put("艾伦", "1001");
        map.put("过去", "1002");
        map.put("以后", "1003");
        map.put("明天", "1004");
        map.put("未来", "1005");
        set<entry<string,string>> set = map.entryset();
        iterator<entry<string,string>> it = set.iterator();
        while(it.hasnext()){
            entry<string, string> e = it.next();
            system.out.println(e.getkey()+"="+e.getvalue());
        }
    }
}

TreeMap中文排序,TreeMap倒序输出排列