2011-02-02 135 views
0

有人可以給一個例子和輸出使用比較器在Java中對數組進行排序嗎? 我知道我需要使用public static void sort(List list, Comparator c);,但比較器如何更改排序順序?在Java中排序集合

+2

開始通過閱讀這篇:http://download.oracle.com/javase/1.4.2/docs/api/java /util/Comparator.html – 2011-02-02 01:30:21

+1

以下是指向當前API版本的鏈接:http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html – jzd 2011-02-02 01:42:22

回答

4

正常情況下,您可以實施Comparable並將列表傳遞給sort()方法。但是,如果你需要使用一個Comparator代替這裏是一個完整的例子:

public static void main(String args[]) { 
    List<ExampleItem> examples = new LinkedList<ExampleItem>(); 
    //Build List 
    Collections.sort(examples, new ExampleCompartor());//Sort with your comparator 
} 

//Custom Class to sort 
class ExampleItem{ 
    private int data; 
} 

//Compartor 
static class ExampleCompartor implements Comparator<ExampleItem>{ 
    @Override 
    public int compare(ExampleItem ex1, ExampleItem ex2) { 
     return ex1.data - ex2.data; 
    } 
} 
2
public class CompSample { 
    public static int countVowels(String s) { 
     return s.replaceAll("[^aeiouAEIOU]", "").length(); 
    } 

    public static class NumberOfVowelsComparator implements Comparator<String> { 
     public int compare(String o1, String o2) { 
      int o1vowels = countVowels(o1); 
      int o2vowels = countVowels(o2); 

      return o2vowels - o1vowels; 
     } 
    } 

    public static void main(String[] args) { 
     String[] words = {"one", "two", "tree", "four"}; 
     List<String> sortedWords = Collections.sort(Arrays.asList(words), 
      new NumberOfVowelsComparator()); 
     System.out.println(sortedWords); 
    } 
}