java treemap用法_Java TreeMap使用方法

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

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

3、使用比较器类来来实现排序,自定义类型不用来继承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

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

return -1;

}

return 0;

}  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值