有序的TreeSet和TreeMap
package myTest;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.TreeSet;
public class Test15_有序的TreeSet和TreeMap {
public static void main(String[] args) {
TreeSet<String> set1=new TreeSet<>();
set1.add("dad");
set1.add("ewqeq");
set1.add("fsfe");
set1.add("mjh");
set1.add("fgh");
set1.add("plj");
set1.add("aasdf");
//String类型默认按照字符顺序
for (String s : set1) {
System.out.println(s);
}
System.out.println("-------------------------");
//自定义Class类型必须定义比较器
TreeSet<Student> set=new TreeSet<Student>(new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.score > o2.score ? 1 : (o1.score == o2.score ? 0 : -1);
}
});
set.add(new Student(12, 99, 182));
set.add(new Student(13, 90, 182));
set.add(new Student(14, 83, 174));
set.add(new Student(14, 50, 178));
set.add(new Student(16, 70, 185));
set.add(new Student(16, 57, 170));
for (Student student : set) {
System.out.println(student);
}
System.out.println("=======================");
TreeMap<String, Integer> map1=new TreeMap<>();
map1.put("weqw", 1);
map1.put("asda", 2);
map1.put("zsa", 3);
map1.put("qw", 5);
map1.put("fd", 4);
//key为String类型,默认按照字符顺序
for (Entry<String,Integer> entry : map1.entrySet()) {
System.out.println(entry.getKey()+","+entry.getValue());
}
System.out.println("---------------");
//key为自定义Class类型,必须定义比较器
TreeMap<Student, Integer> map2=new TreeMap<>(new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
return o1.score > o2.score ? 1 : (o1.score == o2.score ? 0 : -1);
}
});
map2.put(new Student(12, 99, 182), 1);
map2.put(new Student(13, 90, 182), 2);
map2.put(new Student(14, 83, 174), 3);
map2.put(new Student(16, 70, 185), 5);
map2.put(new Student(16, 57, 170), 4);
for (Entry<Student, Integer> entry : map2.entrySet()) {
System.out.println(entry.getKey()+","+entry.getValue());
}
}
}