码迷,mamicode.com
首页 > 编程语言 > 详细

【java】用HashMap计数,用TreeSet排序

时间:2017-03-26 21:26:58      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:div   one   import   main   dff   img   package   rgs   tostring   

技术分享
 1 package com.tn.hashMap;
 2 
 3 import java.util.HashMap;
 4 import java.util.TreeSet;
 5 
 6 public class HashMapDemo {
 7     public static void main(String[] args){
 8         
 9         String str="eeeeaccbbddddffffff";
10         HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
11         for(int i=0;i<str.length();i++){
12             if(!hashMap.containsKey(str.substring(i, i+1))){
13                 hashMap.put(str.substring(i, i+1), 1);
14             }else{
15                 hashMap.put(str.substring(i,i+1), hashMap.get(str.substring(i, i+1))+1);
16             }
17         }
18         
19         TreeSet<T> treeSet=new TreeSet<T>();
20         for(String key:hashMap.keySet()){
21             T t=new T(key,hashMap.get(key));
22             treeSet.add(t);
23         }
24         System.out.println(treeSet);
25     }
26 }
27 
28 class T implements Comparable<T>{
29     private String value;
30     private Integer count;
31     
32     public T(String value, Integer count) {
33         super();
34         this.value = value;
35         this.count = count;
36     }
37 
38     public String getValue() {
39         return value;
40     }
41 
42     public void setValue(String value) {
43         this.value = value;
44     }
45 
46     public Integer getCount() {
47         return count;
48     }
49 
50     public void setCount(Integer count) {
51         this.count = count;
52     }
53 
54     @Override
55     public String toString() {
56         return value+"出现"+count+"次。";
57     }
58 
59     @Override
60     public int compareTo(T o) {
61         if(this.count!=o.count)
62             return this.count-o.count;//以出现次数排序
63         else
64             return this.value.compareTo(o.value);//出现次数相同以字母顺序排序
65     }
66     
67 }
View Code

 

【java】用HashMap计数,用TreeSet排序

标签:div   one   import   main   dff   img   package   rgs   tostring   

原文地址:http://www.cnblogs.com/xiongjiawei/p/6623926.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!