Created
November 5, 2014 00:40
-
-
Save mnstrspeed/f5bb287cf443c2f0c168 to your computer and use it in GitHub Desktop.
Comparator<T> example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.Comparator; | |
public class Test | |
{ | |
public static void main(String[] args) | |
{ | |
Integer[] numbers = { 1, 5, 2, 7, 2, 42, 1 }; | |
// sort ascending | |
Arrays.sort(numbers, new Comparator<Integer>() { | |
public int compare(Integer a, Integer b) | |
{ | |
// if a > b, then result will be positive -> a after b | |
// if b > a, then result will be negative -> b after a | |
return a - b; | |
} | |
}); | |
System.out.println("Ascending:"); | |
for (int i = 0; i < numbers.length; i++) | |
System.out.println(numbers[i]); | |
// sort descending | |
Arrays.sort(numbers, new Comparator<Integer>() { | |
public int compare(Integer a, Integer b) | |
{ | |
return b - a; // reversed | |
} | |
}); | |
System.out.println("\nDescending:"); | |
for (int i = 0; i < numbers.length; i++) | |
System.out.println(numbers[i]); | |
// also works for List<...> type (or ArrayList, LinkedList, etc.), | |
// using Collections.sort(...) instead of Arrays.sort(...) | |
List<Integer> numberList = Arrays.asList(numbers); | |
Collections.sort(numberList, new Comparator<Integer>() { | |
public int compare(Integer a, Integer b) | |
{ | |
return a - b; | |
} | |
}); | |
System.out.println("\nSorted List<Integer>:"); | |
for (Integer n : numberList) | |
System.out.println(n); | |
Integer[][] lists = { | |
{ 2, 4, 3 }, | |
{ 32, 34, 1, 54, 3, 1 }, | |
{ 2, 4, 3, 6, 1 }, | |
{ 1, 4 } | |
}; | |
// sort by list length | |
Arrays.sort(lists, new Comparator<Integer[]>() { | |
public int compare(Integer[] a, Integer[] b) | |
{ | |
// if length of list a > length of listb, | |
// then result will be positive -> a after b | |
// if length of list b > length of list a, | |
// then result will be negative -> b after a | |
return a.length - b.length; | |
} | |
}); | |
System.out.println("\nSorted by list length:"); | |
for (int i = 0; i < lists.length; i++) | |
System.out.println("List of length " + lists[i].length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment