2014-10-03 73 views
-1

我依然没有得到前40名乐下令牛逼我告诉你我的代码:打印前40个元素的值

Map<String, Integer> doubleCount= new HashMap<>(); 
SortedMap<String,Integer> newMap= new TreeMap<>(doubleCount); 
Map<String,Integer> newDouble40 = newMap.headMap("40"); 
System.out.println(newDouble40); 

这是给我一个空的列表,更重要的是它不排序它....所以我整理吧:

public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){ 
    List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet()); 
    Collections.sort(entries, new Comparator<Map.Entry<K,V>>() { 

     @Override 
     public int compare(Entry<K, V> o1, Entry<K, V> o2) { 
      return o2.getValue().compareTo(o1.getValue()); 
     } 
    }); 
    Map<K,V> sortedMap = new LinkedHashMap<K,V>(); 

    for(Map.Entry<K,V> entry: entries){ 
     sortedMap.put(entry.getKey(), entry.getValue()); 
    } 

    return sortedMap; 
} 

,但我如何打印前40 ....如果你使用上面的代码,并说:

System.out.println(sortByValues(doubleCount)); 

您通过值获得了一个已排序的hashMap。

但是我该如何打印第一个40?

回答

0

尝试:

int i = 0; 
for(Map.Entry<K,V> entry: sortByValues(doubleCount)){ 
    System.out.println(entry.getKey() + ": " + entry.getValue()); 
    if (++i == 40) break; 
} 

+0

谢谢你=它工作:-) – Mira 2014-10-04 23:26:28

0

你能不能使用HashMap中的

"public Collection<V> values()" 

函数来获取所有的值,则使用

for(int i=0; i<40; i++){System.out.println(valuelist.get(i))} 
+0

谢谢...它的作品! – Mira 2014-10-04 23:26:46

+0

你应该点击剔/ upvote帮助你的职位。 – rnso 2014-10-05 01:23:10