2016-10-01 81 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

相关问题