2016-10-01 57 views
-3

我有一個不同長度的字符串數組列表。我想將字符串分組,並將它們放入相應長度的不同ArrayList中,並將每個組的ArrayList映射到hashmap。 like:map.put(4,list4);是指列出4的長度是所有單詞4.我有一個不同長度的字符串arraylist。我想組字符串

+0

現在你到目前爲止 –

+0

開始讀文件,存儲的所有串在一個ArrayList中後。現在我正在迭代這個ArrayList。例如對於第一個元素,檢查它的長度並將該長度存儲在一個正在跟蹤長度的數組中。如果一個長度不在這個數組中,我創建一個新的ArrayList將新的長度字放入該列表中,並且還將長度放在數組中,我保留長度信息。如果我已經有長度數組的長度,我只是去那個列表並存儲字符串。 – OsamaKhalid

回答

0
package javaapplication13; 

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.HashMap; 

public class JavaApplication13 { 

    public static void main(String[] args) { 
    // TODO code application logic here 
    BufferedReader br; 
    String strLine; 
    ArrayList<String> arr =new ArrayList<>(); 
    HashMap<Integer,ArrayList<String>> hm = new HashMap<>(); 
    try { 
     br = new BufferedReader(new FileReader("words.txt")); 
     while((strLine = br.readLine()) != null){ 
      arr.add(strLine); 
     } 
    } catch (FileNotFoundException e) { 
     System.err.println("Unable to find the file: fileName"); 
    } catch (IOException e) { 
     System.err.println("Unable to read the file: fileName"); 
    } 


    ArrayList<Integer> lengths = new ArrayList<>(); //List to keep lengths information 


    System.out.println("Total Words: "+arr.size()); //Total waords read from file 

    int i=0; 
    while(i<arr.size()) //this loop will itrate our all the words of text file that are now stored in words.txt 
    { 
     boolean already=false; 
     String s = arr.get(i); 
     //following for loop will check if that length is already in lengths list. 
     for(int x=0;x<lengths.size();x++) 
     { 
      if(s.length()==lengths.get(x)) 
       already=true; 
     } 
     //already = true means file is that we have an arrayist of the current string length in our map 
     if(already==true) 
     { 

      hm.get(s.length()).add(s); //adding that string according to its length in hm(hashmap) 
     } 
     else 
     { 
       hm.put(s.length(),new ArrayList<>()); //create a new element in hm and the adding the new length string 
       hm.get(s.length()).add(s); 
       lengths.add(s.length()); 

     } 

     i++; 
    } 
    //Now Print the whole map 
    for(int q=0;q<hm.size();q++) 
    { 
     System.out.println(hm.get(q)); 
    } 
    } 

} 
+0

我有不同長度的字符串文件,我想根據長度對它們進行分組,然後做那些你所建議的東西。如果一個字符串的長度爲4。比我會映射像:map.put(「4」,list1)。意味着列表將只有那些長度爲4的字符串。問題是我不知道文件中有多少個不同的長度單詞。 – OsamaKhalid

+0

因此,讓我們看看你有什麼(代碼)開始,然後我們幫助你。 –

+0

如何在這裏粘貼代碼。評論只有200個字符,我認爲。 – OsamaKhalid

相關問題