2016-03-02 95 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