2016-04-04 4 views
0

だけのjava ...これらのアイテムを含む結果リストにのみオブジェクトを追加する方法は?唯一のレシピに表示されるショッピングリストの項目を保つためにのArrayListにオブジェクトを追加する方法をマッチ含まれているアイテムなど[茶、牛乳、砂糖]</p> <p>と私のレシピオブジェクト成分リストがある別のリストとしての項目が含まれています、私はShoppingList 2つのArrayListつのリストを持っている

final List<RecipeN> result = new ArrayList<RecipeN>(); 
     for (RecipeN rn : allrec) { 
      for (ShoppingList sl : allitems) { 
       for(int i = 0;i<rn.getIngredient().size();i++) { 
        if (rn.getIngredients(i).contains(sl.getrName())) { 
         result.add(rn); 
        } 
       } 
      } 





public class RecipeN { 
    private String recName; 
    private List<String> ingredient = new ArrayList<String>(); 

    public RecipeN(){ 

    } 
    public RecipeN(String item){ 
     this.ingredient.add(item); 
    } 

    public List<String> getIngredient(){ 
     return ingredient; 
    } 
    public String getIngredients(int i){ 

     return ingredient.get(i); 
    } 
    public void setIngredient(List<String> item){ 
     this.ingredient = item; 
    } 

    public String getRecName() { 
     return recName; 
    } 

    public void setRecName(String recName) { 
     this.recName = recName; 
    } 

    @Override 
    public String toString() { 
     return recName; 
    } 
} 

答えて

0

使用方法retainAll(Collection c): 問題は、これらのアイテムの両方のリストに共通の項目を見つけ 私のコードが含まれていて、複数のオブジェクトを追加することです。コード例は以下の通りです:

List<Item> recipe = new ArrayList<>(); 
List<Item> shoppingList = new ArrayList<>(); 

... your code ... 

shoppingList.retainAll(recipe); 
0

あなたは、リスト内の重複を持たないためにHashSetを使用する必要がありますのみ1回各一致レシピを持っているしたい場合。

final Set<RecipeN> result = new HashSet<RecipeN>(); 
for (RecipeN rn : allrec) { 
    for (ShoppingList sl : allitems) { 
     for(int i = 0;i<rn.getIngredient().size();i++) { 
      if (rn.getIngredients(i).contains(sl.getrName())) { 
       result.add(rn); 
      } 
     } 
    } 
} 

あなたはそれを行うことができますArrayListのを維持したい場合:

final Set<RecipeN> result = new HashSet<RecipeN>(); 
for (RecipeN rn : allrec) { 
    boolean recipeMatched = false; 
    for (ShoppingList sl : allitems) { 
     for(int i = 0;i<rn.getIngredient().size();i++) { 
      if (rn.getIngredients(i).contains(sl.getrName())) { 
       recipeMatched = true; 
       result.add(rn); 
       break; 
      } 
      if (recipeMatched) 
       break; 
     } 
     if (recipeMatched) 
      break; 
    } 
} 
関連する問題