Demo07_TreeMap.java 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package J20250723;
  2. import java.util.Comparator;
  3. import java.util.Set;
  4. import java.util.TreeMap;
  5. /**
  6. * @author WanJl
  7. * @version 1.0
  8. * @title Demo07_TreeMap
  9. * @description
  10. * @create 2025/7/23
  11. */
  12. public class Demo07_TreeMap {
  13. public static void main(String[] args) {
  14. TreeMap<Student,String> map=new TreeMap((Comparator<Student>) (o1, o2) -> {
  15. int r=o2.getId()-o1.getId();
  16. r=r==0?o1.getName().compareTo(o2.getName()):r;
  17. return r;
  18. });
  19. Student s1=new Student(1001,"张三1");
  20. Student s2=new Student(1002,"张三2");
  21. Student s3=new Student(1003,"张三3");
  22. Student s4=new Student(1004,"张三4");
  23. map.put(s1,"北京");
  24. map.put(s2,"上海");
  25. map.put(s3,"广州");
  26. map.put(s4,"深圳");
  27. //获取key的集合
  28. Set<Student> students = map.keySet();
  29. for (Student s:students){
  30. //get获取值
  31. String addr = map.get(s);
  32. System.out.println(s+"->"+addr);
  33. }
  34. }
  35. }