如何在 Java 中使用定制的 Comparator 对数组进行排序?
假设以下内容是我们的字符串数组且我们需要对它进行排序
String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" };
在 sort() 方法中,创建一个 Comparator 来对上述字符串进行排序。在此处,两个字符串进行比较,然后继续进行此过程
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("
Sorted array..."); for (String res : str) System.out.print(res + " "); } }
输出
Array... Tom Jack Harry Zen Tim David Sorted array... David Harry Jack Tim Tom Zen
广告