针对字符串数组进行排序和倒序排列

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));
        }
    }
}
 1 import java.util.Arrays;
 2 import java.util.Collections;
 3 import java.util.List;
 4 
 5 public class SortDemo {
 6 
 7     public static void main(String[] args) {
 8     String[] suits = { "Hearats", "Diamonds", "Clubs", "Spades" };
 9 
10     List<String> list = Arrays.asList(suits);
11     System.out.printf("Unsorted array elements: %s%n", list);
12 
13     Collections.sort(list);
14     System.out.printf("Sorted array elements: %s%n", list);
15     
16     Collections.sort(list, Collections.reverseOrder());
17     System.out.printf("Reverse sorted array elements: %s%n", list);
18     } // end method main
19 } // end class SortDemo

 图片 1

 

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

图片 2

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图