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]
發佈了51 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章