Sort Collections in Java
Can someone please give an example and output of sorting an array in Java using a com开发者_StackOverflow中文版parator?
I know I need to use public static void sort(List list, Comparator c);
, but how does the comparator change the sorting order?
Normally you can just implement Comparable
and just pass the List to the sort()
method. But if you need to use a Comparator
instead here is a full example:
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;
}
}
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);
}
}
Here is a good example of how to sort using comparator. http://www.javadeveloper.co.in/java-example/java-comparator-example.html
精彩评论