java中实现汉字按照拼音排序(示例代码)
投稿:jingxian
最近項目中需要對繁體字按拼音進行排序
public static void main(String[] args) {
Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
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]);
}
[code]
package zhouyrt;
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;
}
}