Java中对汉字按拼音排序的方法,简体繁体均有效。
Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
String[] arr = { "张三", "李四", "王五", "刘六" ,"周濤","戴笠","戴阿"}; String[] arr1 = {"生活","文教","政治","自然","宗教","經貿","軍事","经贸"};
//對簡體字有效,戴阿、戴笠在第一個字相同的情況下按拼音比較第二個字,很智能哦 Arrays.sort(arr, cmp); for (int i = 0; i < arr.length; i++) //輸出:戴阿、戴笠、李四、刘六、王五、张三、周濤 System.out.println(arr[i]);
//對繁體字無效,繁體的“軍事”被拍到了最后 Arrays.sort(arr1, cmp); for (int i = 0; i < arr1.length; i++) //輸出:经贸、生活、文教、政治、自然、宗教、經貿、軍事 System.out.println(arr1[i]); }
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class PinyinPaixu { static class Person {
private String name; private Integer salary;//薪水 private Integer age;//年齡
Person(String n, Integer s, Integer a) { this.name = n; this.salary = s; this.age = a; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }
public String toString() { return "姓名:" + this.name + "\t薪水:" + this.salary + "\t年齡:" + this.age; } } /* * 按薪水排序,從低到高 */ static class SalaryComparator implements Comparator { public int compare(Object o1, Object o2) {
Integer salary1 = ((Person)o1).salary; Integer salary2 = ((Person)o2).salary; if(salary1 - salary2 > 0) return 1; if(salary1 - salary2 < 0) return -1; else return 0; } } /* * 按年齡排序,從低到高 */ static class AgeComparator implements Comparator { public int compare(Object o1, Object o2) {
Integer age1 = ((Person)o1).age; Integer age2 = ((Person)o2).age; if(age1 - age2 > 0) return 1; if(age1 - age2 < 0) return -1; else return 0; } }
List<Person> list = new ArrayList<Person>(); list.add(new Person("張洋",3400,25)); list.add(new Person("王肅",10000,27)); list.add(new Person("李安",9000,30)); list.add(new Person("劉虎",2500,22)); list.add(new Person("安德剛",3500,21)); Person[] personAry = new Person[list.size()]; personAry = list.toArray(new Person[list.size()]);
System.out.println("--- 排序前 ------------------------------------"); for(Person p : personAry) { System.out.println(p); } Arrays.sort(personAry,new SalaryComparator()); System.out.println("--- 按薪水排序后 ------------------------------------"); for(Person p : personAry) { System.out.println(p); }
Arrays.sort(personAry,new AgeComparator()); System.out.println("--- 按年齡排序后 ------------------------------------"); for(Person p : personAry) { System.out.println(p); }
} } --- 排序前 ------------------------------------ --- 按薪水排序后 ------------------------------------ --- 按年齡排序后 ------------------------------------ |