zoukankan      html  css  js  c++  java
  • TreeSet按value排序

    今天学习到TreeSet,但是它是按照key的值来排序的,那如果我们想要按照value的值排序呢?这个问题我上网看了好久,终于找到一个比较易懂的例子:

    例:(统计输入数字的个数)

    话不多说,看代码就懂

    import java.util.*;
    import java.util.Scanner;
    
    public class CountNum {
      public static void main(String[] args){
    
        HashMap<Integer, Integer> hashMap = new HashMap<Integer,Integer>();
    	Scanner input = new Scanner(System.in);
    	int num = input.nextInt();
        while (num != 0) 
    	{
    		if(hashMap.get(num) == null)
    		{
    		  hashMap.put(num,1);
    		}
    		else
    		{
    			int value = hashMap.get(num).intValue();
    			value++;
    			hashMap.put(num,value);
    		}
    		num = input.nextInt();
    	}
    
        // Create a tree map from the hash map
        TreeMap<Integer, Integer> treeMap =
          new TreeMap<Integer, Integer>(hashMap);
    
    	Set<Map.Entry<Integer,Integer>> entrySet = treeMap.entrySet();
    
    	ArrayList<Count> list = new ArrayList<Count>();
    	for(Map.Entry<Integer,Integer> entry:entrySet){
    		Count cc = new Count(entry.getKey(),entry.getValue());
    		list.add(cc);
    	}
    	Collections.sort(list);
    /*
    	for(int i = 0; i< list.size();i++){
    		System.out.println(list.get(i).getKey() + "	" + list.get(i).getValue());
    	}
    */
    
    //找出多个最大值
    	int i = 0;
    	for(; i< list.size()-1;i++){
    		if(list.get(i).getValue() > list.get(i+1).getValue())
    		{
    			System.out.println(list.get(i).getKey() + "	" + list.get(i).getValue());
    			break;
    		}
    		else if(list.get(i).getValue() == list.get(i+1).getValue() && i+1 < list.size())
    		{
    			System.out.println(list.get(i).getKey() + "	" + list.get(i).getValue());
    
    		}
    	}
    	if(i == list.size() -1 )
    		System.out.println(list.get(i).getKey() + "	" + list.get(i).getValue());
    
      }
    }
    
    class Count implements Comparable {
      int key;
      int value;
    
      public int getKey(){
    	  return key;
      }
      public int getValue(){
    	  return value;
      }
      public Count(int key, int value) {
        this.key = key;
        this.value = value;
      }
    
      public int compareTo(Object o) {
        return -(value - ((Count)o).value);
      }
    
      public boolean equals(Object o) {
        return value == ((Count)o).value;
      }
    }
    
  • 相关阅读:
    【转】一个java处理JSON格式数据的通用类
    Oracle数据类型Clob读取
    【网摘】Ibatis调用存储过程
    jQuery实现页面模块拖拽与模块自定义效果.rar
    jspSmartUpload上传下载全攻略
    【转】JSON 入门指南
    【摘选自江苏移动网上营业厅】JS实现无间断向上滚动marquee
    Oracle用户解锁
    js 蒙版进度条(图片)
    java文件夹遍历
  • 原文地址:https://www.cnblogs.com/sysu-blackbear/p/3245543.html
Copyright © 2011-2022 走看看