2016-03-02 79 views
0

我試圖通過讓listOfProducts和ittirating過它來過濾產品..要根據產品的價格過濾產品和打印將過濾

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

可能是其很容易的一個,但沒有得到如何從列表中打印出降低過濾產品

感謝

+0

至於你的代碼,你有一個錯誤在這裏。然而,如果'if'方法'filterByPrice'將返回一個沒有任何過濾的列表 –

回答

0

這樣做的最好的辦法就是Java 8流

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

您可以在這裏添加很多其他類型的產品處理。見java.util.stream.Stream的Javadoc

+0

非常感謝你..它工作seamlesslly ... :) – SNK

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