2016-10-01 5 views
0
public class JavaApplication13 { 

    /** 
    * @param args the command line arguments 
    */ 
    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)); 
     } 
    } 

} 

このアプローチは正しいですか?長さに基づいてテキストファイルからArraylistへの単語のグループ化

説明:

  1. 負荷のArrayListへのすべての単語。
  2. 次に、各インデックスを繰り返し、単語の長さをチェックして、その長さを含む文字列のArrayListに追加します。これらの文字列は、含まれる単語の長さのハッシュマップにマップされます。

答えて

1

まず、行全体を単語として処理しているため、コードは1行ずつ含むファイルに対してのみ機能します。あなたは言葉にそれを分割して、各ラインを処理する必要があなたのコードはより普遍的なようにするには:

String[] words = strLine.split("\\s+") 

第二に、あなたは、任意の一時的なデータ構造を必要としません。ファイルから行を読み込んだ直後に、マップに単語を追加することができます。 arrlengthsのリストは一時的な格納以外のロジックを含んでいないので実際には無用です。 lengthsリストを使用して、hmマップに既に追加されている長さを保存するだけです。 hm.containsKey(s.length())を呼び出すことで同じことができます。

そして、あなたのコードの追加コメント:

for(int x=0;x<lengths.size();x++) { 
     if(s.length()==lengths.get(x)) 
      already=true; 
    } 

あなただけのときにループ続行する必要はありませんいくつかの条件が任意の要素のために真である場合に見つける必要があるときにこのようなループを持っています条件が既に見つかりました。ループブロックを終了するには、if文内にbreakキーワードを使用する必要があります。

for(int x=0;x<lengths.size();x++) { 
     if(s.length()==lengths.get(x)) 
      already=true; 
      break; // this will terminate the loop after setting the flag to true 
    } 

しかし、すでに言及したように、それはまったく必要ありません。それは単に教育目的のためです。

+0

非常に役に立ちます私は変更を加えるつもりです – OsamaKhalid

1

あなたのアプローチは長く、混乱し、デバッグが難しく、パフォーマンスが良くないと思っています(containsの方法を参照)。これを確認してください:

String[] words = {"a", "ab", "ad", "abc", "af", "b", "dsadsa", "c", "ghh", "po"}; 
Map<Integer, List<String>> groupByLength = 
    Arrays.stream(words).collect(Collectors.groupingBy(String::length)); 
System.out.println(groupByLength); 

これは単なる例ですが、その点が分かります。私は言葉の配列を持っているし、私はストリームとJava8の魔法を使用して長さ(正確にあなたがしようとしているもの)でそれらをグループ化します。あなたはストリームを取得し、単語の長さでグループ化してマップに集めるので、リストの1文字ごとにキー1などのリストに入れます。

同じアプローチを使用できますが、リスト内の単語はArrays.stream()ではなく、.stream()をあなたのリストに入れてください。

+0

私は今からストリームを使用するつもりです。良い応答 – OsamaKhalid

関連する問題