简体   繁体   中英

Comparing for a given value in a list of objects - java 8

I have list of Objects

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 in java 8 streams.

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


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM