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;
      }
    }
    
  • 相关阅读:
    apache log4j打印日志源码出口
    filter listener interceptor的区别
    搭建oracle linux虚拟机报错解决
    top命令查看进程下线程信息以及jstack的使用
    关于跨域访问
    跨域访问
    一直性hash解决扩容后的hash算法不用变
    _创建日志_
    oracle读写文件--利用utl_file包对磁盘文件的读写操作
    oracle中utl_file包读写文件操作实例学习
  • 原文地址:https://www.cnblogs.com/sysu-blackbear/p/3245543.html
Copyright © 2011-2022 走看看