我有两个Arraylist一个List是ShoppingList,其中包含[茶,牛奶,糖]等项目
和另一个List是我的食谱对象成分列表...那么如何只在包含这些项目的结果列表中添加对象? 问题是它添加多个对象包含这些项 我的代码在两个列表中找到共同的项目:
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 :(得分:0)
使用方法retainAll(Collection c)
仅将商品保留在配方中显示的购物清单中。代码示例如下:
List<Item> recipe = new ArrayList<>();
List<Item> shoppingList = new ArrayList<>();
... your code ...
shoppingList.retainAll(recipe);
答案 1 :(得分:0)
如果你想每个匹配配方只有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;
}
}