List 排序 Java工具类详解编程语言

/** 
############################################################################# 
# DESCRIBE 关于给Vector,ArrayList和LinkedList特定List集合排序的方法 
# AUTHOR  
# DATE 2007-3-16 
# COMPANY FLX 
# PORJECT JAVA 
############################################################################# 
*/ 
import java.io.PrintStream; 
import java.text.CollationKey; 
import java.text.Collator; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 
 
public class SortList { 
 
 public static void main(String args[]) { 
  String words[] = { "man", "Man", "Woman", "woman", "Manana", "manana", "ma?ana", "Ma?ana", "Mantra", "mantra", 
    "mantel", "Mantel" }; 
 
  PrintStream out = System.out; 
 
  List list = new ArrayList(Arrays.asList(words)); 
  out.println("传入的list:"); 
  out.println(list); 
  out.println(); 
 
  Collections.sort(list); 
  out.println("默认的sorting:"); 
  out.println(list); 
  out.println(); 
 
  list = new ArrayList(Arrays.asList(words)); 
  Comparator comp = Collections.reverseOrder(); 
  Collections.sort(list, comp); 
  out.println("反向sorting:"); 
  out.println(list); 
  out.println(); 
 
  list = new ArrayList(Arrays.asList(words)); 
  comp = new CollatorComparator(); 
  Collections.sort(list, comp); 
  out.println("自定义排序sorting:"); 
  out.println(list); 
  out.println(); 
 
  list = new ArrayList(Arrays.asList(words)); 
  comp = new CaseInsensitiveComparator(); 
  Collections.sort(list, comp); 
  out.println("按照语种sorting:"); 
  out.println(list); 
  out.println(); 
 
 } 
 
 /** 
  ############################################################################# 
  # 
  # @DESCRIBE 自定义的排序规则 
  # @author Administrator 
  # 
  ############################################################################# 
  */ 
 public static class CaseInsensitiveComparator implements Comparator { 
  public int compare(Object element1, Object element2) { 
   String lower1 = element1.toString().toLowerCase(); 
   String lower2 = element2.toString().toLowerCase(); 
   return lower1.compareTo(lower2); 
  } 
 } 
 /** 
  ############################################################################# 
  # 
  # @DESCRIBE 按照语种进行排序的规则 
  # @author Administrator 
  # 
  ############################################################################# 
  */ 
 public static 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); 
  } 
 } 
}

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10937.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论