java中可以排序的工具类和接口共有五个SortedMap 、SortedSet、TreeMap 、TreeSet和Collections,Collections中需要显式调用sort()方法。

     事例如下:

 


java实现中文汉字的首字母排序_java代码


1. import
2. import
3. import
4. import
5. import
6. import
7. import
8. import
9. import
10. import
11. import
12.
13. public class
14. public
15. }
16.
17. /**
18. * 数组的中文排序
19. */
20. public void
21.
22. "中山", "汕尾", "广州", "汕头", "阳江"};
23. Arrays.sort(sortArray);
24. for (int i = 0; i < 5; i++) {
25. System.out.println( (String) sortArray[i]);
26. }



//结果排序为:中山,广州,汕头,汕尾,阳江。按照每个单词最后一个字母的降序进行排列。



1. String[] reverseArray = {"中山", "汕尾", "广州", "汕头", "阳江"};
2. Collections.reverse(Arrays.asList(reverseArray));
3. for (int i = 0; i < 5; i++) {
4. System.out.println( (String) reverseArray[i]);
5. }


//结果排序为:阳江,汕头,广州,汕尾,中山。Coleections的反序(reverse)是指单词进行首末对换

//按照中文第一个字母升序排列的实现




1. import
2. import
3. import
4. public class
5. /**
6. * @param args
7. */
8. public static void
9. // TODO Auto-generated method stub
10. Comparator<Object> com=Collator.getInstance(java.util.Locale.CHINA);
11. "中山","汕头","广州","安庆","阳江","南京","武汉","北京","安阳","北方"};
12. Arrays.sort(newArray,com);
13. for(String i:newArray){
14. " ");
15. }
16. }
17. }


//结果的排序为:安庆 安阳 北方 北京 广州 南京 汕头 武汉 阳江 中山




1. public void
2. new
3. "中山");
4. "汕尾");
5. "广州");
6. "汕头");
7. "阳江");
8.
9. new
10. Collections.sort(sortList,comparator);
11. for(int i=0;i<sortList.size();i++){
12. //因为ArrayList实现的是RandomAccess 随机访问接口。使用get()要比迭代的效率高。
13. //如果实现的是SequenceAccess(顺序访问接口。如:LinkList),使用迭代的效率高。
14. System.out.println(sortList.get(i));
15. }


//结果的排序为:广州,汕头,汕尾,阳江,中山。

//也可以使用Object[] listToArray=sortList.toArray();转换成数组后再进行排序


1. Object[] listToArray=sortList.toArray();
2. Arrays.sort(listToArray, comparator);
3. for (int i = 0; i < listToArray.length; i++) {
4. System.out.println( (String) listToArray[i]);
5. }


//结果的排序为:广州,汕头,汕尾,阳江,中山。



1. public void
2. // 按照键值排序
3. new
4. new
5. "中山", "a");
6. "广州", "b");
7. "潮州", "c");
8. //注意:每次对TreeMap进行put()时,TreeMap都会自动调用它的compare(key,Entry.key)
9. //按照key进行排序
10. Collection col = sortMap.keySet();
11. Iterator it = col.iterator();
12. while
13. System.out.println(it.next());
14. }
15.
16. }


//排序结果是:潮州,广州,中山。
public static void main(String[] args){
mySort mysort=new mySort();

//看看数组的中文排序
mysort.arraySort();

//看看链表的中文排序
mysort.listSort();

//看看map的中文排序
mysort.mapSort();
}

} //重写compare方法



1. package
2. import
3. import
4. import
5.
6. public class myComparator implements
7.
8. //关于Collator。
9. private Collator collator = Collator.getInstance();//点击查看中文api详解
10.
11. public
12. }
13.
14.
15. /**
16. * compare
17. * 实现排序。
18. * @param o1 Object
19. * @param o2 Object
20. * @return int
21. */
22. public int
23.
24. //把字符串转换为一系列比特,它们可以以比特形式与 CollationKeys 相比较
25. //要想不区分大小写进行比较用o1.toString().toLowerCase()
26. CollationKey key2=collator.getCollationKey(o2.toString());
27.
28. return key1.compareTo(key2);//返回的分别为1,0,-1 分别代表大于,等于,小于。要想按照字母降序排序的话 加个“-”号
29. }
30. }