集合之TreeMap

TreeMap

底层数据结构是二叉树
如何保证键的唯一: 利用存的特点
如何保证键的可排序: 利用取的特点 左跟右
在map中数据结构只对键有效
TreeMap 有Map的键值对的特性:还可以进行排序,默认自然排序


利用正则和TreeMap 实现一段英文的单词记录

  

 1 String str = "Failure is probably the, fortification in your pole. " +
 2                 "It is like a peek your wallet as. the thief, when you are" +
 3                 " thinking how to spend several? hard-won lepta, when you " +
 4                 "are wondering whether ?new money, it has laid background." +
 5                 " Because of you, then at the heart of the most lax, alert," +
 6                 " and most " +
 7                 "low awareness, and left it godsend failed.";
 8 
 9 String s = "\\d+.\\d+|\\w+";//正则表达式
10 Pattern  pattern=Pattern.compile(s);  
11 Matcher  ma=pattern.matcher(str);  
12 
13 
14 
15 TreeMap<String, Integer> tree = new TreeMap<String,Integer>();
16 
17 while(ma.find()){
18     
19     String c = ma.group();//获取用正则取出来的单词
20     
21     if(!tree.containsKey(c)){//去重和计数
22         tree.put(c, 1);
23     }else{
24         int num = tree.get(c)+1;
25         tree.put(c, num);
26     }            
27 }
28 
29 //遍历:
30 Set<String> set = tree.keySet();
31 for (String key : set) {
32     System.out.println(key+"("+tree.get(key)+")");
33 }
34 
35 
36 //TreeMap排序:
37 TreeMap<Person,String> map =new TreeMap<Person,String>(new java.util.Comparator<Person>(){//实现Comparator接口
38 
39     @Override
40     public int compare(Person o1, Person o2) {//按实际要求重写该方法,必要时使用三门运算符
41         return -(o1.getHandsome()-o2.getHandsome());
42     }
43     
44 } );

 

  

posted @ 2018-08-02 16:14  风中雨雨中路  阅读(111)  评论(0编辑  收藏  举报