专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java技术分享,treemap使用方法

Java技术分享,treemap使用方法

更新时间:2020-05-25 16:10:24 来源:动力节点 浏览1779次

使用默认的TreeMap 构造函数,其中key值需要有比较规则。

使用默认的TreeMap 构造函数,Key中添加自定义类型,自定义类型必须继承Comparator。

使用比较器类来来实现排序,自定义类型不用来继承Comparator

试例代码:

public class Demo {
   public static void main(String[] args) {
   //1、使用默认的TreeMap 构造函数,其中key值需要有比较规则
   TreeMap map =new TreeMap<>();
     map.put(new Integer(2), "BB");
   map.put(new Integer(1), "AA");
   map.put(new Integer(5), "EE");
   map.put(new Integer(3), "CC");
   map.put(new Integer(4), "DD");
   map.put(new Integer(2), "AA");   //验证重复key是否能够插入
     //使用遍历EntrySet方式
   for(Entry entry:map.entrySet()){
    System.out.println("Key:"+entry.getKey()+ " --- value:"+entry.getValue());
   }
      //2、使用默认的TreeMap 构造函数,Key中添加自定义类型,自定义类型必须继承Comparator
   System.out.println("-------------------2、使用默认的TreeMap 构造函数,Key中添加自定义类型,自定义类型必须继承Comparator-----------------------");
   TreeMap mapPer=new TreeMap<>();
   mapPer.put(new person("张三",22), "6K");
   mapPer.put(new person("老王",35), "29K");
   mapPer.put(new person("小张",31), "11K");
         for(Entry entry:mapPer.entrySet()){
    System.out.println("Key:"+entry.getKey()+ " --- value:"+entry.getValue());
   }
      //3、使用比较器类来来实现排序,自定义类型不用来继承Comparator
   System.out.println("-------------------3、使用比较器类来来实现排序,自定义类型不用来继承Comparator-----------------------");
   TreeMap mapBook =new TreeMap<>(new BookComparator());
   mapBook.put(new Book("流浪地球",60),"200页");
   mapBook.put(new Book("三体",100),"400页");
   mapBook.put(new Book("大秦帝国",180),"900页");
      for(Entry entry:mapBook.entrySet()){
    System.out.println("Key:"+entry.getKey()+ " --- value:"+entry.getValue());
   }
   }   }
//自定义person类
class person implements Comparable {
 String name;  int age;
   public person(String name,int age) {
   this.name=name;
   this.age=age;  }
   @Override
 public String toString() { 
    return "姓名:"+this.name +" 年龄:" +this.age;
 }
 @Override
 public int compareTo(person o) {
  if(o.age>this.age) {
   return 1;
  } else if(o.age<this.age) {
   return -1;
  }
  return 0;
 }  }
//自定义book类
class Book {
 String name;
 double price;
   public Book(String name,double price) {  
   this.name=name;
    this.price=price;  }
   @Override
 public String toString() {
  return "书名:"+this.name+" 价格:"+this.price;
 }  }
//book比较器类
class BookComparator implements Comparator{
 @Override
 public int compare(Book o1, Book o2) {
  if(o1.price>o2.price) {
   return 1;
  } else if(o1.price<o2.price) {
   return -1;
  }
  return 0;
 }  }

Java技术相关内容

Java TreeMap排序:http://www.bjpowernode.com/tutorial_java_advance/609.html

以上就是动力节点java培训机构的小编针对“Java技术分享,treemap使用方法”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>