如何使用Java中的自定义比较器对数组进行排序?
假设以下是我们的字符串数组,我们需要对其进行排序:
String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" };
在该sort()
方法内,创建一个自定义比较器以对上述字符串进行排序。这里,将两个字符串相互比较,然后继续进行该过程:
Arrays.sort(str, new Comparator < String > () { public int compare(String one, String two) { int val = two.length() - one.length(); if (val == 0) val = one.compareToIgnoreCase(two); return val; } });
示例
import java.util.Arrays; import java.util.Comparator; public class Demo { public static void main(String[] args) { String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" }; System.out.println("Array..."); for (String res : str) System.out.print(res + " "); Arrays.sort(str, new Comparator<String>() { public int compare(String one, String two) { int val = two.length() - one.length(); if (val == 0) val = one.compareToIgnoreCase(two); return val; } }); System.out.println("\nSorted array..."); for (String res : str) System.out.print(res + " "); } }
输出结果
Array... Tom Jack Harry Zen Tim David Sorted array... David Harry Jack Tim Tom Zen