2017-04-06 78 views
-1

我已將單詞文件轉換爲字符串數組。我需要以某種方式將數組轉換爲字長列表並使其可搜索。換句話說,我需要能夠輸入一個單詞長度(比如5),並且只能顯示單詞長度爲5的單詞。幫幫我?詞典詞典:需要掃描每個元素的詞長度並使其可搜索

public static void main(String[] args) throws IOException {  
    String token1 = ""; 
    Scanner scan = new Scanner(new File("No.txt")); 
    List<String> temps = new ArrayList<String>(); 
    while (scan.hasNext()){ 
      token1 = scan.next(); 
      temps.add(token1); 
    } 
    scan.close(); 
    String[] tempsArray = temps.toArray(new String[0]); 
    for (String s : tempsArray) { 
+0

循環遍歷數組,比較長? – tnw

+1

查看[Google Guava的'Multimap'](https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap),例如你可以使用'Multimap '來收集單詞的長度。 – Thomas

+0

對我的回答有任何意見/反饋?它有幫助嗎?我可以添加一些東西以便讓你接受嗎? – GhostCat

回答

4

你不使用數組。你需要的東西是收藏品,更確切地說:MapsLists;因爲你想使用Map<Integer, List<String>>

含義:使用「字長」作爲關鍵字的地圖;並且映射的條目是包含具有該長度的所有單詞的列表。下面是一些代碼,讓你開始:

Map<Integer, List<String>> wordsByLength = new HashMap<>(); 
// now you have to fill that map; lets assume tempsArray contains all your words 
for (String s : tempsArray) { 
    List<String> listForCurrentLength = wordsByLength.get(s.length()); 
    if (listForCurrentLength == null) { 
    listForCurrentLength = new ArrayList<>(); 
    } 
    listForCurrentLength.add(s); 
    wordsByLength.put(s.length(), listForCurrentLength); 

的想法基本上是遍歷數組你已經有;併爲每個字符串在那裏...把它放入該地圖;取決於其長度。

(上面只是寫下來,既不編譯,也不測試;如說是指「僞代碼」讓你去)