javajava-8java-stream

Comparing for a given value in a list of objects using Java 8 streams


I have List<Product>.

class Product{

  String productName;
  int mfgYear;
  int expYear;
} 


int testYear = 2019;
List<Product> productList = getProductList();

I have list of products here.

Have to iterate each one of the Product from the list and get the List<String> productName that lies in the range between mfgYear & expYear for a given 2019(testYear).

For example, 
mfgYear <= 2019 <= expYear 

How can I write this using Java 8 streams?


Solution

  • You can write as following:

    int givenYear = 2019;
    
    List<String> productNames = 
                      products.stream()
                              .filter(p -> p.mfgYear <= givenYear && givenYear <= p.expYear)
                              .map(Product::name)
                              .collect(Collectors.toList());
    
    // It would be more clean if you can define a boolean function inside your product class
    
    class Product {
    // your code as it is
    boolean hasValidRangeGiven(int testYear) {
           return mfgDate <= testYear && testYear <= expYear:
    }
    
    List<String> productNames = products.stream()
                                        .filter(p -> p.hasValidRange(givenYear))
                                        .map(Product::name)
                                        .collect(Collectors.toList());