本文主要是介绍TreeMap集合的不同键值类型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
TreeMap:是基于红黑树的Map接口的实现。
该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的
Comparator 进行排序,具体取决于使用的构造方法。TreeMap<String,String>
键:String
值:String
//创建集合对象TreeMap<String,String> tm=new TreeMap<String,String>();tm.put("hello", "h2o");tm.put("world", "w3ld");tm.put("java", "j4a");tm.put("world", "3kdn");tm.put("ok", "dkls");//键集合Set<String> set=tm.keySet();for(String key:set){String value=tm.get(key);System.out.println(key+"---"+value);}
TreeMap<Student,String>
键:Student
值:String
//创建集合对象//泛型为对象的时候需要重写ComparatorTreeMap<Student,String> tm=new TreeMap<Student,String>(new Comparator<Student>() {public int compare(Student s1,Student s2){int num=s1.getAge()-s2.getAge();int num2=num==0?s1.getName().compareTo(s2.getName()):num;return num2;}});Student s1=new Student("马云",34);Student s2=new Student("马化腾",45);Student s3=new Student("雷军",44);Student s4=new Student("马化腾",45);tm.put(s1, "h2o");tm.put(s2, "h24");tm.put(s3, "h45");tm.put(s4, "h47");//键集合Set<Student> set=tm.keySet();for(Student key:set){String value=tm.get(key);System.out.println(key.getName()+"---"+key.getAge()+"---"+value);}
这篇关于TreeMap集合的不同键值类型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!