需求:商品售出件数排行TOP5
解决办法:采用MAP的值排序
代码:
我们可以将Map集合转换成List集合中,而List使用ArrayList来实现 List<Map.Entry<ReportResult, Integer>> list = new LinkedList(map.entrySet()); // 最后通过Collections.sort(List l, Comparator c)方法来进行排序 Collections.sort(list, new Comparator<Map.Entry<ReportResult, Integer>>() { public int compare(Map.Entry<ReportResult, Integer> o1, Map.Entry<ReportResult, Integer> o2) { return (o2.getValue() - o1.getValue()); } }); //组装 int i = 1; Map result = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); result.put(entry.getKey(), entry.getValue()); i++; if (i == 5) { break; } }