对map排序

1.利用TreeMap中的tailMap方法:
  Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
package map;
import java.util.TreeMap;

public class MapTestApp {
       
        public static TreeMap myDataBase = new TreeMap();

        public static void main(String[] args) {
                int initID = (int)(Math.random()*12345);
                Student[] s = new Student[10];
                myDataBase.put(0, "tdfkdsfkdsf");
                for(int i=0;i<s.length;i++) {
                        s[i] = new Student(initID,"John","China");                       
                        myDataBase.put(new Integer(initID),s[i]);
                        initID = (int)(Math.random()*12345);
                }
                System.out.println(myDataBase.tailMap(myDataBase.firstKey()).toString());
  //表示所有元素后面一个的key大于等于前面一个的key值.
        }
}
2.对中文排序:
package map;

import java.util.Collection;

import java.util.Iterator;

import java.util.SortedMap;

import java.util.TreeMap;

public class TestSort {

 
 public static void main(String[] args) {

  // TODO Auto-generated method stub

  CollatorComparator comparator = new CollatorComparator();

  TreeMap map = new TreeMap(comparator);

  map.put("", "请选择");
  for (int i = 0; i < 10; i++) {

   String s = "" + (int) (Math.random() * 1000);

   map.put(s, s);
  }

  map.put("abcd", "abcd");

  map.put("Abc", "Abc");

  map.put("bbb", "bbb");

  map.put("BBBB", "BBBB");

  map.put("北京", "北京");

  map.put("中国", "中国");

  map.put("上海", "上海");

  map.put("厦门", "厦门");

  map.put("香港", "香港");

  map.put("碑海", "碑海");

  Collection col = map.values();

  Iterator it = col.iterator();

  while (it.hasNext()) {

   System.out.println(it.next());

  }

 }

}

import java.text.CollationKey;
import java.text.Collator;
import java.util.Comparator;

public class CollatorComparator implements Comparator {

 Collator collator = Collator.getInstance();

 public int compare(Object element1, Object element2) {

  CollationKey key1 = collator.getCollationKey(element1.toString());

  CollationKey key2 = collator.getCollationKey(element2.toString());

  return key1.compareTo(key2);

 }

}
注意:The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.
关键是getCollationKey:Transforms the String into a series of bits that can be compared bitwise to other CollationKeys. 将中文转化为一系列二进制位,所以能对中文排序.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值