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. 将中文转化为一系列二进制位,所以能对中文排序.