TreeMap 判断两个 key 相等的标准:两个 key 通过 compareTo() 方法或者 compare() 方法返回 0 。
示例:
package com.github.map.demo7;
import java.util.Map;
import java.util.TreeMap;
/**
* @author maxiaoke.com
* @version 1.0
*/
public class Test {
public static void main(String[] args) {
Map<String, Integer> map = new TreeMap<>();
map.put("c", 25);
map.put("h", 18);
map.put("a", 21);
map.put("b", 98);
System.out.println("map = " + map);
}
}
示例:
package com.github.map.demo8;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
/**
* @author maxiaoke.com
* @version 1.0
*/
public class Test {
public static void main(String[] args) {
Map<Person, String> map = new TreeMap<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
map.put(new Person("张三", 18), "大一");
map.put(new Person("李四", 20), "大一");
map.put(new Person("王五", 19), "大二");
map.put(new Person("赵六", 23), "大四");
map.put(new Person("田七", 17), "大一");
System.out.println("map = " + map);
}
}