TreeMap
package com.zzp.demo; import java.util.Map; import java.util.TreeMap; /** * * 测试TreeMap * @author java * */ public class TestTreeMap { public static void main(String[] args) { Map<Integer,String> treeMap1 = new TreeMap<>(); treeMap1.put(30, "aa"); treeMap1.put(2, "bb"); treeMap1.put(10, "cc"); for(Integer key : treeMap1.keySet()){ System.out.println(key + "---" +treeMap1.get(key)); } Map<Emp,String> treeMap2 = new TreeMap<>(); treeMap2.put(new Emp(100,"张三",1000), "张三真垃圾"); treeMap2.put(new Emp(200,"李四",10000), "李四真棒棒"); treeMap2.put(new Emp(150,"王五",100), "王五更垃圾"); treeMap2.put(new Emp(50,"赵六",2000), "赵六也垃圾"); treeMap2.put(new Emp(300,"钱七",2000), "钱七也垃圾"); for(Emp key : treeMap2.keySet()){ System.out.println(key +"----"+ treeMap2.get(key)); } } } class Emp implements Comparable<Emp>{ int id; String name; int salary; public Emp(int id, String name, int salary) { super(); this.id = id; this.name = name; this.salary = salary; } @Override public int compareTo(Emp o) { //负数小于0,整数大于0,等于0 if(this.salary > o.salary){ return 1; }else if(this.salary < o.salary){ return -1; }else{ if(this.id > o.id){ return 1; }else if(this.id < o.id){ return -1; }else{ return 0; } } } @Override public String toString() { // TODO Auto-generated method stub return "id:"+id+",name:"+name+",salary:"+salary; } }