java 集合 TreeMap中文排序

package cn.hncu.col.sort.v4;

import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import cn.hncu.col.sort.V3.Person;

public class SortDemo4 {
	/* 
	 * 该版本展示中文排序即按汉语拼音的先后顺序排
	 */
	public static void main(String[] args) {
		TreeMap map = new TreeMap( new MyCmp2() );
		map.put("周平", new Person("周平",30));
		map.put("张三", new Person("张三",20));
		map.put("李四", new Person("李四",25));
		map.put("老王", new Person("老王",21));
		map.put("aa", new Person("aa",23));
		map.put("猛男", new Person("猛男",23));
		
		Set entrySet=map.entrySet();
		Iterator it=entrySet.iterator();
		while(it.hasNext()){
		 Entry en=(Entry) it.next();
		 System.out.println(en.getKey()+","+en.getValue());
		}

	}

}

package cn.hncu.col.sort.v4;

import java.text.CollationKey;
import java.text.Collator;
import java.util.Comparator;

public class MyCmp2 implements Comparator {
	//Collator 类执行区分语言环境的 String 比较。使用此类可为自然语言文本构建搜索和排序例程。
	private Collator collator=Collator.getInstance();
	
	
	
	/*o1和o2是含中文的字符串(map中的key),
	 * 现在想让o1和o2按中文拼音的先后顺序排序,则根据先后关系分别返回:
	 * 负整数、0或正整数
	 */
	@Override
	public int compare(Object o1, Object o2) {
		CollationKey key1=collator.getCollationKey(o1.toString());
		CollationKey key2=collator.getCollationKey(o2.toString());
		
		return key1.compareTo(key2);
	}

}

public class Person {
 private String name;
 private int age;
public Person(String name, int age) {

	this.name = name;
	this.age = age;
}
/* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + age;
	result = prime * result + ((name == null) ? 0 : name.hashCode());
	return result;
}
/* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Person other = (Person) obj;
	if (age != other.age)
		return false;
	if (name == null) {
		if (other.name != null)
			return false;
	} else if (!name.equals(other.name))
		return false;
	return true;
}
/**
 * @return the name
 */
public String getName() {
	return name;
}
/**
 * @param name the name to set
 */
public void setName(String name) {
	this.name = name;
}
/**
 * @return the age
 */
public int getAge() {
	return age;
}
/**
 * @param age the age to set
 */
public void setAge(int age) {
	this.age = age;
}
/* (non-Javadoc)
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
	return  name + ", " + age;
}
 
}

猜你喜欢

转载自blog.csdn.net/lx678111/article/details/79824473