我正在研究java需求,我需要根据几个条件删除一些ArrayList元素。
这是我的代码:
package com.demo.test;
public class ProductBean {
public ProductBean(int code,String name,String type,String status){
this.productCode=code;
this.productType=type;
this.productName=name;
this.productStatus=status;
}
public int getProductCode() {
return productCode;
}
public void setProductCode(int productCode) {
this.productCode = productCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
private String productName;
private String productType;
private String productStatus;
private int productCode;
public String toString(){
return"prduct details are : "+this.productCode+" "+this.productName+" "+this.productType+" "+this.productStatus;
}
}
测试类:
package com.demo.test;
import java.util.ArrayList;
import java.util.Iterator;
public class ProductTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProductBean p1=new ProductBean(1, "product1", "toy", "S1");
ProductBean p2=new ProductBean(2, "product2", "toy", "S1");
ProductBean p3=new ProductBean(3, "product3", "toy", "S1");
ProductBean p4=new ProductBean(4, "product4", "toy", "S1");
ProductBean p5=new ProductBean(5, "product5", "toy", "S2");
ProductBean p6=new ProductBean(6, "product6", "toy", "S2");
ProductBean p7=new ProductBean(7, "product7", "toy", "S2");
ProductBean p8=new ProductBean(8, "product8", "toy", "S2");
ProductBean p9=new ProductBean(9, "product9", "toy", "S2");
ArrayList<ProductBean> productList=new ArrayList<ProductBean>();
productList.add(p1);
productList.add(p2);
productList.add(p3);
productList.add(p4);
productList.add(p5);
productList.add(p6);
productList.add(p7);
productList.add(p8);
productList.add(p9);
int requiredProductCode=2;
String requiredProductStatus="S1";
Iterator<ProductBean> itr=productList.iterator();
while(itr.hasNext()){
ProductBean pbean=itr.next();
if(pbean.getProductCode()<=requiredProductCode){
itr.remove();
}
if(!pbean.getProductStatus().equals(requiredProductStatus)){
itr.remove();
}
}
for(ProductBean pbean1:productList){
System.out.println(pbean1);
}
}
}
我必须根据以下条件从列表中删除产品对象。
期望/实际输出
prduct details are : 3 product3 toy S1
prduct details are : 4 product4 toy S1
我尝试使用AND(&amp;&amp;)OR(||)运算符但未获得所需的输出来实现此目的。我最终在while循环中使用了两个if条件.Kindly改进了对这段代码的建议改进。使用一些逻辑运算符来避免代码中的两个条件。
答案 0 :(得分:0)
现在,如果两个if
语句中的条件都为真,那么您将删除两个而不是一个。您可以将第二个else if
或两者合并为一个if
,如下所示:
if ((bean.getProductCode()<=requiredProductCode) || (!pbean.getProductStatus().equals(requiredProductStatus)))