TreeMap集合

package com.bo.collection;

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

//TreeMap 存储结构 红黑树
public class Demo16 {
public static void main(String[] args) {
//创建元素
TreeMap<People,String> student =new TreeMap(new Comparator<People>() {
@Override
public int compare(People o1, People o2) {
int n1 =o1.getName().compareTo(o2.getName());
int n2 =o1.getAge()-o2.getAge();
return n1==0?n2:n1;
}
});
People p1 =new People("李白",18);
People p2 =new People("华佗",17);
People p3 =new People("曹操",17);
People p4 =new People("无名",20);
//添加元素
student.put(p1,"高2.2");
student.put(p2,"高1.3");
student.put(p3,"高1.4");
student.put(p4,"高3.1");
System.out.println("元素个数:"+student.size());
System.out.println(student.toString());
//删除
student.remove(p1);
System.out.println("删除之后:"+student.size());
//student.clear(); 清空
//遍历
System.out.println("--------keySet-------------");
Set<People> s = student.keySet();
for (People people : s) {
System.out.println(people+":"+student.get(people));
}
System.out.println("-----------entrySet-------------");
Set<Map.Entry<People,String>> v=student.entrySet();
for (Map.Entry<People, String> p : v) {
System.out.println(p.getKey()+":"+p.getValue());
}
//判断
System.out.println(student.containsKey(p2));
System.out.println(student.containsValue("MMP"));

}
}
上一篇:集合9、集合_Map接口_TreeMap类


下一篇:十大排序算法——桶排序