Java 用TreeMap 储存自定义对象 并按名称排序

package Map.Demo;

import TreeSet.*;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {

	public static void main(String[] args) {
 
	/*
	 * 将学生对象和学生的归属地通过键与值储存到map集合中
	 *  
	 *  
	 */
	TreeMap tm=new TreeMap(new COM());
		tm.put(new Students("lisi", 38),"北京");
		tm.put(new Students("zhaoliu", 24),"上海");
		tm.put(new Students("xiaoqiang", 31),"沈阳");
		tm.put(new Students("wangcai", 28),"大连");
		tm.put(new Students("zhaoliu", 24),"铁岭");

		Iterator>it=tm.entrySet().iterator();
	
		
		while(it.hasNext()) {
			Map.Entryme=it.next();
			Students key=me.getKey();
			String value=tm.get(key);
			System.out.println(key.getName()+":"+key.getAge()+"---"+value);
		}
	} 

}
package Map.Demo;

import java.util.Comparator;

public class COM implements Comparator{

	@Override
	public int compare(Person o1, Person o2) {
		int temp=o1.getName().compareTo(o2.getName());
		return temp==0?o1.getAge()-o2.getAge():temp;
	}
	

}


 
  


你可能感兴趣的:(Java学习)