1. 程式人生 > >物件放在TreeMap根據中文名字排序:

物件放在TreeMap根據中文名字排序:

1、首先自定義一個Comparator:

public class SortStrUtil implements Comparator<String> {
	//這個類是處理中文排序的關鍵
	private Collator collator=Collator.getInstance();	
	@Override
	public int compare(String s1, String s2) {
		CollationKey key1 = collator.getCollationKey(s1);
		CollationKey key2 = collator.getCollationKey(s2);
		return key1.compareTo(key2);
	}	
}

2、建立一個Student類:

public class Student implements Serializable{
	private int id;
	private String name;
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}

3、測試類:

public class TestStudent {
	@Test
	public void testStudent() {
		Student s1=new Student(1,"中國",21);
		Student s2=new Student(1,"美國",21);
		Student s3=new Student(1,"英國",21);
		TreeMap<String, Student> tm=new TreeMap<>(new SortStrUtil());
		tm.put(s1.getName(), s1);
		tm.put(s2.getName(), s2);
		tm.put(s3.getName(), s3);
		Set<String> keySet = tm.keySet();
		Iterator<String> iterator = keySet.iterator();
		while(iterator.hasNext()) {
			Student student = tm.get(iterator.next());
			System.out.println(student);
		}
	}
}

測試結果,中文根據拼音排序了:

Student [id=1, name=美國, age=21]
Student [id=1, name=英國, age=21]
Student [id=1, name=中國, age=21]