0

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?

1
  • 1
    what have you tried so far? Commented Sep 15, 2020 at 3:30

2 Answers 2

1

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());


Sign up to request clarification or add additional context in comments.

Comments

0
List<String> process(List<Product> productList) {
    return productList.stream()
            .filter(this::isWithinRange)
            .map(Product::getProductName)
            .collect(Collectors.toList());
}

boolean isWithinRange(Product product) {
    return product.mfgYear <= 2019 && product.expYear <= 2019;
}

static class Product {

    String productName;
    int mfgYear;
    int expYear;

    public String getProductName() {
        return productName;
    }
}

filter() will pass any item for which the lambda expression (or method reference in this case) return true. map() will convert the value passing the item to the method reference and create a stream of whatever type it returns. We pass the name getter in that case.

1 Comment

Thanks for the answer..Is there a way to pass a testYear variable from isWithinRange as my comparing year will change between every check..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.