2014-10-02 135 views
0

我試圖顯示出17K中的前40條記錄,我已將其存儲在地圖中。我有以下代碼在已排序的地圖中顯示第一條記錄

import java.util.*; 
Map<String, Integer> doubleCount= new HashMap<String,Integer>(); 
.... 
Map<String,Integer> newDouble40 = doubleCount.headMap(40); 

的Java是給我下面的錯誤:

" cannot find symbol - method subMap... 

所以我嘗試:

Map<String,Integer> newDouble40 = doubleCount.subMap("",(Integer)40); 

以及確切的錯誤是: 無法找到符號 - 方法subMap(java.lang.String,java.lang.int)

http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html 我該如何排序?

+3

'subMap'是'SortedMap'的一種方法,但您的'doubleCount'對象具有抽象的'Map'接口作爲其靜態類型,而且未排序的'HashMap'也是動態類型。所以,如果你需要的話,首先使用'SortedMap'。 – 5gon12eder 2014-10-02 04:41:44

回答

4

subMap()headMap()兩種方法在SortedMap那些不具備Map

你可以嘗試以下方法

Map<String, Integer> doubleCount= new HashMap<String,Integer>(); 
SortedMap<String, Integer> newMap= new TreeMap<>(doubleCount); 
Map<String,Integer> newDouble40 = newMap.subMap("0","40"); 

你的情況KeysString,所以你必須subMap("0","40")String值。 0是開始鍵,「40」是結束鍵。您的newDouble40的元素有一個在040之間的密鑰。

在這裏您可以使用headMap()作爲newMap.headMap("40")。現在您將獲得具有小於40的關鍵點的元素。

如:

Map<String, Integer> doubleCount= new HashMap<>(); 
doubleCount.put("c",1); 
doubleCount.put("d",2); 
doubleCount.put("a",1); 
doubleCount.put("b",4); 
SortedMap<String, Integer> newMap= new TreeMap<>(doubleCount);//sorted now 
Map<String,Integer> map1 = newMap.subMap("a", "c"); 
Map<String,Integer> map2 = newMap.headMap("c"); 
System.out.println(map1); 
System.out.println(map2); 

輸出地說:

{a=1, b=4} 
{a=1, b=4} 
+0

感謝您的幫助,我過去了那個錯誤,但我的問題依然存在,請看下面我的回答 - – Mira 2014-10-02 16:57:46

0

主要這裏的問題是,你正在嘗試使用(java.util.SortedMap中)子接口的方法,接口沒有按地圖不暴露headMap(...)或subMap(...)方法。

正確的代碼,將編譯將是:

你應該考慮
SortedMap<String, Integer> doubleCount = new TreeMap<String, Integer>(); 

Map<String, Integer> newDoubleCount = doubleCount.headMap("40"); 

的一件事是什麼,該SortedMap的方法返回一個基於密鑰參數的地圖的一部分,與鍵比較在地圖中,除非你知道第40個元素的鍵值是多少,否則你不能使用這些方法。

+0

請看下面 – Mira 2014-10-02 16:56:55