想要根据产品的价格过滤产品并打印过滤产品

时间:2016-03-02 17:35:15

标签: java

我试图通过获取listOfProducts并对其进行过滤来过滤产品..

public List<Products> filterByPrice(int min,int max){   

    List<Products> listofproducts = products.retrieveProducts();
    System.out.println(listofproducts +" size: " +listofproducts.size());

    for (Products productsVar : listofproducts) {
        if(productsVar.getPrice()>= min && productsVar.getPrice()<= max){
            return  listofproducts; //here how do i print the reduced listOfProducts
        }
    }       
    return null;
}

可能是非常简单但不能从列表中打印出经过简化过滤的产品

由于

3 个答案:

答案 0 :(得分:1)

您正在打印并返回整个列表,请尝试以下操作:

List<Products> listofproducts = New List<Products>();
//System.out.println(listofproducts +" size: " +listofproducts.size());

for (Products productsVar : products.retrieveProducts()){ 
    if(productsVar.getPrice()>= min && productsVar.getPrice()<= max){
       listofproducts.add(productsVar);
    }
return  listofproducts; // may return blank list if no products fall between min and max price range

答案 1 :(得分:0)

执行此操作的最佳方法是Java 8 Streams

List<Products> filteredListOfProducts = listofproducts.stream()
  .filter(p -> p.getPrice >= min && p.getPrice() <= max)
  .collect(Collectors.toList());
...
return filteredListOfProducts;

您可以在这里添加许多其他类型的产品处理。请参阅java.util.stream.Stream javaDoc

答案 2 :(得分:0)

此代码是为产品添加价格范围和价值过滤器 如果错误,请更正:) 将此方法添加到您的sevlet

public int[] getMaxMinForConstraint() {
    int[] array = new int[4]; //statement

    String query = "SELECT  min(price),max(price),min(owners),max(owners) from products";

    PreparedStatement pst = null;
    ResultSet rs = null;
    try {
        pst = conn.prepareStatement(query);
        rs = pst.executeQuery();
        if (rs != null) {

            if(rs.next()) {

              for(int i=1;i<=4;i++)
              {
                  array[i-1]=rs.getInt(i);
              }

然后将此代码添加到您的jsp或html中,以插入价格滑块和所有者数量输入框

 <div class="slider">
                        <label>Custom Price</label>
                        <div id="price" data-min="0" data-max=" 
<%=getMaxMinForContraint[1]%>" data-min-name="min_price" data-max-name="min_price" 
 data-unit="USD" class="slider" aria-disabled="false"></div>
                        <div class="clearfix"></div>
                    </div>

<div class="form">
                        <div class="input">
                            <select id="owners" class="form">
                                <option value="">&nbsp;</option>
                                <%for (int i = getMaxMinForConstraint[3]; i <= maxminValuesForSearch[4]; i++) {%>
                                <option value="<%=i%>"><%=i%></option>
                                <%}%>
                            </select>
                            <i class=""></i>
                        </div>
                    </div>

<button class="btn" onclick="myfun()">Find Product</button>

然后添加此功能以查找产品

  function myfun()
  {

    var $min_price = $("#price").slider("values", 0);
    var $max_price = $("#price").slider("values", 1);
    var $owners = $("#owners").val();

    if ($min_price == null || $min_price == "" || $min_price < 0)
        $min_price = -1;
    if ($max_price == null || $max_price == "" || $max_price < 0)
        $max_price = -1;

    if ($owners == null || $owners == "" || $owners < 0)
        $owners = -1;

    var obj = {
        "min_price": $min_price,
        "max_price": $max_price,
        "owners": 
    };
    //alert(JSON.stringify(obj));
    // console.log(JSON.stringify(obj));
    var string = ""
    $.ajax({
        type: "post",
        url: "SearchProduct",
        //cache: false,
        data: JSON.stringify(obj),
        success: function (result) {

            manageHtml(result);
        },
        error: function () {
            alert("Request can not Proceed at this time");
        }
    });
}

function manageHtml($r)
{

    var $str;
    var $table = $("#example1").DataTable();
    $("#arrnum").text($r.length);
    $("#example1").empty();

    //$("#tb1").html("");
    for (var i = 0; i < $r.length; i++)
    {

        }

        $str = "<tr><td><div class=\'col-lg-12 col-md-12\'><div class=\'product listing, product 1\'><div class=\'product\'><a href=\'SingleProduct.jsp?id=" + $r[i].id + "\'><img src=\'" + $r[i].pictures + "\' class=\'img-fluid \' alt=\'\'><\/a>" <h4 class=\'productname\'><a href=\'SingleProduct.jsp?id=" + $r[i].id + "\'>" + $r[i].name + "<\/a><\/h4><img src=\'\/img\/addProduct.png\' class=\'img-fluid'><\/a><\/div><\/div><div class=\'price\'><h4 class=\'price\'>$ " + ($r[i].price) + " <\/h4><\/div><div class=\'detail-btn\'><a href=\'SingleProduct.jsp?id=" + $r[i].id + "\' class=\'more-btn\'>More Info<\/a><\/div><\/div><\/div><\/div><\/div><\/td><\/tr>";
        console.log($str);
        $("#example1").append($str);

最后将以下代码添加到您的搜索产品servlet

    String jsonString = "";
            BufferedReader br
                    = new BufferedReader(new 
   InputStreamReader(request.getInputStream()));

            String json = "";
            if (br != null) {
                jsonString = br.readLine();
                System.out.println("recieve" + jsonString);
            }
            System.out.println(jsonString != null);
            if (jsonString != null /*&& logged_in && role.compareToIgnoreCase("buyer")==0*/) {
                int buyer_id = ((BuyerDAO) session.getAttribute("buyer")).getId();

                JSONObject obj = new JSONObject(jsonString);

                int min_price, max_price, 
                int owners;
                min_price = obj.getInt("min_price");
                max_price = obj.getInt("max_price");
                owners = obj.getInt("owners");


                String condition = "";
                if (min_price != -1) {
                    condition += "price>=" + min_price + " And ";
                }
                if (max_price != -1) {
                    condition += "price<=" + max_price + " And ";
                }

                if (owners != -1) {
                    condition += "owners=" + owners + " And ";
                }

                condition += "1=1";

                ProductDB db = new ProductDB();
                //set buyer id from seesion
                JSONArray arr = new JSONArray(db.getAllProducts(condition, buyer_id));
                // System.out.println("recieve" + obj.toString());
                out.println(arr.toString());
            } else {
                out.println("0");
            }
        } else {
            out.println("0");
        }