java中的TreeMap

首先举例基本的用法:TreeMap默认是按照key进行排序,要是遇到key相同的话,只输出一个数值。

1.基础用法

package testpro;

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

public class Demo2 {
	
	public static void main(String[] args) {
		TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
		
		tm.put("a", 1);
		tm.put("ab", 15);
		tm.put("ba", 51);
		tm.put("bc", 19);
		tm.put("a", 17);
		tm.put("da", 0);
		
		
		Set<Entry<String, Integer>> set1 = tm.entrySet();
		
		for(Entry<String, Integer> s: set1) {
			System.out.println(s.getKey() + ":" + s.getValue());
		}

	}

}

结果如下:

a:17
ab:15
ba:51
bc:19
da:0

2.升级版

我这里根据TreeMap的性质对其进行功能拓展:
我想对学生按照年龄进行从大到小排序,要是年龄相同,就根据名字排序,所以将学生的信息封装在Student的类中,然后将这个类放在TreeMap的key的位置,再传入一个比较器,就可以进行比较

这是Student类:

package testpro;

public class Student{
	private String name;
	private int age;
	
	
	
	public Student() {}
	
	public Student(String name, int age) {
		
		this.name = name;
		this.age = age;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public void setName(String name) {
		this.name = name;
		
	}
	
	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}

	}

这是比较类:

package testpro;

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

public class Demo2 {
	//TreeMap默认是按照key进行排序,要是遇到key相同的话,只输出一个数值。
	public static void main(String[] args) {
		TreeMap<Student, Integer> tm = new TreeMap<Student, Integer>(new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				if(o1.getAge() == o2.getAge()) {
					return o1.getName().compareTo(o2.getName());
				}
				return o2.getAge() - o1.getAge();
			}
			
		});
		
		Student s1 = new Student("a",2);
		Student s2 = new Student("ab",23);
		Student s3 = new Student("a",28);
		Student s4 = new Student("ba",29);
		Student s5 = new Student("ca",2);
		
		tm.put(s1,1);
		tm.put(s2,1);
		tm.put(s3,1);
		tm.put(s4,1);
		tm.put(s5,1);
		
		
		Set<Entry<Student, Integer>> set1 = tm.entrySet();
		
		for(Entry<Student, Integer> s: set1) {
			System.out.println(s.getKey());
		}

	}

}

结果如下:

Student [name=ba, age=29]
Student [name=a, age=28]
Student [name=ab, age=23]
Student [name=a, age=2]
Student [name=ca, age=2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值