今天学习到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; } }