认识TreeMap
![](https://i-blog.csdnimg.cn/direct/c19b4c3d772e4948be059d6b722050a2.png)
![](https://i-blog.csdnimg.cn/direct/401bcbed6c6c4bc4af55ef5bcef84356.png)
TreeMap应用
![](https://i-blog.csdnimg.cn/direct/13dd0b5a891547ad8df96fb7bc598065.png)
需求1: 创建集合时使用比较器对象
package com.chen.集合.bao3;
import java.util.Comparator;
import java.util.TreeMap;
public class Demo {
public static void main(String[] args) {
//降序
TreeMap<Integer,String > treeMap=new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
treeMap.put(3,"张三");
treeMap.put(2,"李四");
treeMap.put(1,"王五");
//默认升序
System.out.println(treeMap);
}
}
需求2:自定义对象实现Comparable
package com.chen.集合.bao3;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student{name = " + name + ", age = " + age + "}";
}
@Override
public int compareTo(Student o) {
//按年龄升序排列,年龄一样,按姓名的字母排列
int i = this.getAge() - o.getAge();
//i<0 降序
//i>0 升序
//i=0 相等
if(i==0){
i=this.getName().compareTo(o.getName());
//abcdefg...
}
return i;
}
}
package com.chen.集合.bao3;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
TreeMap<Student, String> treeMap = new TreeMap<>();
Student student1 = new Student("张三", 23);
Student student2 = new Student("李四", 12);
Student student3 = new Student("王五", 39);
treeMap.put(student1,"江苏");
treeMap.put(student2,"上海");
treeMap.put(student3,"北京");
System.out.println(treeMap);
}
}
需求3:统计字母个数
![](https://i-blog.csdnimg.cn/direct/912e55be45e84de5ab3bd8ee6a7a82d3.png)
package com.chen.集合.bao3;
import java.util.TreeMap;
public class Demo1 {
public static void main(String[] args) {
//HashMap:结果不需要排序
//TreeMap:结果需要排序
TreeMap<Character, Integer> map = new TreeMap<>();
String s="abbcccabc";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(map.containsKey(c)){
Integer count = map.get(c);
count++;
map.put(c,count);
}else {
map.put(c,1);
}
}
System.out.println(map);
map.forEach((k,v)->{
System.out.print(k+"("+v+")");
});
}
}