1. 程式人生 > >TreeMap中文排序,TreeMap倒序輸出排列

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

entry color 處理文本 接口 info ima import @override imp

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)); } } }

技術分享圖片

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倒序輸出排列