TreeMap的基本使用

版权声明:关注微信公众号:摸鱼科技资讯,联系我们 https://blog.csdn.net/qq_36949176/article/details/87901404

TreeMap

内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。 

方法一:让对象类实现Comparable接口,覆盖comparaTo方法(略)

方法二:比较器

步骤:

1、新建比较器:

package cn.itcast.p3.comparator;

import java.util.Comparator;

import cn.itcast.p2.bean.Person;

public class ComparatorByName implements Comparator<Person> {

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

}

2、传入比较器

package cn.itcast.p8.treemap.demo;

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

import cn.itcast.p2.bean.Student;
import cn.itcast.p3.comparator.ComparatorByName;

public class TreeMapDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName());
		
		tm.put(new Student("lisi",38),"北京");
		tm.put(new Student("zhaoliu",24),"上海");
		tm.put(new Student("xiaoqiang",31),"沈阳");
		tm.put(new Student("wangcai",28),"大连");
		tm.put(new Student("zhaoliu",24),"铁岭");
		
		
		Iterator<Map.Entry<Student, String>> it = tm.entrySet().iterator();
		
		while(it.hasNext()){
			Map.Entry<Student,String> me = it.next();
			Student key = me.getKey();
			String value = me.getValue();
			
			System.out.println(key.getName()+":"+key.getAge()+"---"+value);
		}
		
	}

}

运行结果

wangcai:28---大连
xiaoqiang:31---沈阳
lisi:38---北京
zhaoliu:24---铁岭

猜你喜欢

转载自blog.csdn.net/qq_36949176/article/details/87901404
今日推荐