2017-12-13 2 views
-1

ある文字列配列の単語が別の文字列配列に含まれているかどうかを調べる方法がわかりません。 .contains()は文字列配列に適用することはできませんので、上記のコードは、現在、私にエラーを与えている文字列配列に別の文字列配列内の単語が含まれていないか確認する

 FileInputStream fis = new FileInputStream("TranHistory.csv"); 
     InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 
     CSVReader reader = new CSVReader(isr); 

     String[] groceries = new String[]{"albertsons", "costco"}; 

     for (String[] cols; (cols = reader.readNext()) != null;) { 
      if(cols[4].toLowerCase().contains(groceries)){ 
       System.out.print(cols[4]); 
      } 

     } 

:これは私がこれまで持っているものです。私はこれにif文を変更する場合、これが作品のみ:

 if(cols[4].toLowerCase().contains("albertsons")){ 
       System.out.print(cols[4]); 
     } 

私の問題がString []食料品は、多くの食料品店を持っているとしているということですので、私は[] StringにString []型COLを比較する食料品がほとんどだと思いますこれを行う効率的な方法私はちょうどそれを実装するのに苦労しています。

SOLUTION:

私はあなたがforループのネストされたをしなければならない...それを考え出しました。これは私がやったことです:

Set<String> groceries = Set.of("albertsons", "costco"); 

for (String[] cols; (cols = reader.readNext()) != null;) { 
    if (groceries.contains(cols[4].toLowerCase()){ 
     System.out.print(cols[4]); 
    } 
} 

それはあなたの場合は同じようにSetで検索すると、線形時間がかかることはありません。

String[] groceries = {"albertsons", "costco"}; 

for (String[] cols; (cols = reader.readNext()) != null;) { 
     for (int i = 0; i < groceries.length; i++){ 

      if(cols[4].toLowerCase().contains(groceries[i])) 
      { 
       System.out.print(cols[4]); 
       } 

      } 
     } 

答えて

2

は、私はあなたが持っていることを計画食料品のすべてを含むSet<String>の作成をお勧めします配列を使用していました。

YCF_Lと私は以下のコメントで説明したように、あなたがたJava 8でSetを初期化することができます:それはむしろ線形時間よりも、一定の時間内の要素を検索すると、私は通常、HashSetのを経由してこれを行うだろう

Set<String> groceries = new HashSet<>(Arrays.asList("albertsons", "costco")); 
+0

私はエラーを取得しています: – Stephan

+1

'を設定#のof'はまだしていない場合は、更新する必要がありますJavaの9に導入されたSet.of方法を解決することはできません! –

+1

更新しない(またはできない)場合は、 'Set'を' new HashSet <>(Arrays.asList( "albertsons"、 "costco")); ' –

0

。したがって、このコードを使用して検索することができます。私はあなたがファイルの元の配列全体が見つかったときに印刷されることを望んでいると仮定しています。

FileInputStream fis = new FileInputStream("TranHistory.csv"); 
InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 
CSVReader reader = new CSVReader(isr); 

String[] groceries = new String[]{"albertsons", "costco"}; 
Set<String> grocerySet = Arrays.stream(groceries).collect(Collectors.toSet()); 
System.out.println(grocerySet); 
for (String[] cols; (cols = reader.readNext()) != null;) { 
    Set<String> smallGrocerySet = Arrays.stream(cols).collect(Collectors.toSet()); 
    if(grocerySet.containsAll(smallGrocerySet)){ 
     System.out.println(Arrays.toString(cols)); 
    } 
} 
関連する問題