java排序接口
算法我不懂,所以直接用现成的东西比较容易。
java api里面实现的排序接口有Collection.sort和TreeMap,sort原理是归并排序,treeMap是红黑树排序。
package com.study.collection; import java.util.*; /** * Created by DELL on 2016-5-12. */ public class Sort { /** * treeMap排序 */ public static void treeMapTest(){ /** * treeMap排序,排序原理是红黑树排序 * 如果没有指定排序器,默认按照key的string的升序排列, * string会先转换成char,如果是中文对转换成中文的unicode编码,把编码的升序排列 * 建议最好指定排序器,否则有中文时会有问题 */ Map<String,String> treeMap = new TreeMap<String,String>(new CollatorComparator()); treeMap.put("zbc","zbc"); treeMap.put("你好","你好"); treeMap.put("111","111"); treeMap.put("北京","北京"); treeMap.put("厦门","厦门"); treeMap.put("碑海","碑海"); System.out.println(treeMap); } /** *Collection排序,排序原理归并排序 */ public static void ListStortTest(){ List<Object> list = new ArrayList<Object>(); list.add("123"); list.add("132"); list.add("abc"); list.add("acc"); list.add("碑海"); list.add("厦门"); list.add("北京"); //排序时如果list的元素没有实现Comparable接口,则必须传入排序器 Collections.sort(list,new CollatorComparator()); System.out.println(list); Collections.reverse(list); System.out.println("逆序"+list); } /** * 实现Comparable接口排序 *Collection排序,排序原理归并排序 */ public static void listSortBeanTest(){ List<SortBean> list = new ArrayList<SortBean>(); list.add(new SortBean("123")); list.add(new SortBean("132")); list.add(new SortBean("abc")); list.add(new SortBean("acc")); list.add(new SortBean("碑海")); list.add(new SortBean("厦门")); list.add(new SortBean("北京")); //排序元素list的元素没有实现Comparable接口,如果传入排序器,则bean的Comparable接口无效 Collections.sort(list/*,new SortBeanComparator()*/); System.out.println(list); } public static void main(String[] args){ //Sort.treeMapTest(); // Sort.ListStortTest(); Sort.listSortBeanTest(); } } package com.study.collection; import java.text.CollationKey; import java.text.Collator; import java.util.Comparator; import java.util.Locale; /** * 排序器 */ public class CollatorComparator implements Comparator<Object> { //本地化语言 Collator collator = Collator.getInstance(Locale.SIMPLIFIED_CHINESE); /** * 重写这个方法,使用简体中文排序 * @param el1 * @param el2 * @return */ public int compare(Object el1,Object el2){ CollationKey key1 = collator.getCollationKey(el1.toString()); CollationKey key2 = collator.getCollationKey(el2.toString()); return key1.compareTo(key2); } } package com.study.collection; import java.text.Collator; import java.util.Comparator; import java.util.Locale; /** * Created by DELL on 2016-5-12. */ public class SortBean implements Comparable<SortBean>{ private String content; Collator collator = Collator.getInstance(Locale.SIMPLIFIED_CHINESE); public SortBean(String content){ this.content = content; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public int compareTo(SortBean o) { return collator.compare(this.getContent(),o.getContent()); } @Override public String toString() { return this.content; } }