簡體   English   中英

如何在僅包含匹配項的Arraylist中添加對象

[英]how to add object in Arraylist which contains matched items only java

我有兩個Arraylist,一個List是ShoppingList,其中包含[tea,milk,sugar]等項目

還有另一個列表是我的食譜對象成分列表...那么,如何僅在包含這些項目的結果列表中添加對象? 問題是它添加的多個對象包含這些項目。我的代碼在兩個列表中都找到共同的項目:

    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;
    }
}

使用方法retainAll(Collection c)僅將商品保留在配方中顯示的購物清單中。 代碼示例如下:

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

... your code ...

shoppingList.retainAll(recipe);

如果您希望每個匹配食譜只有1次,則應使用HashSet ,以確保列表中沒有重復項。

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;
    }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM