首页 > 解决方案 > Pass function as parameter to Lambda java 8

问题描述

I have the following method:

public String getAllDangerousProductsName(Offer offer){
    return offer.getOfferRows().stream()
           .filter(row -> row.isDangerousGood())
            .map(row -> row.getItemInformation().getOfferTexts().getName())
            .collect(Collectors.joining(","));
}

I want to reuse this method for row.isBulkyGood(). What I am doing currently is

public String getAllBulkyProductsName(Offer offer){
    return offer.getOfferRows().stream()
            .filter(row -> row.isBulkyGood())
            .map(row -> row.getItemInformation().getOfferTexts().getName())
            .collect(Collectors.joining(","));
}

... which is basically code repetition. Is there a way I can pass the function as method parameter to optimize this to have one method for both the filter condition?

标签: javalambdajava-8java-stream

解决方案


You can pass the Predicate used in the filter right to the method which is the only thing that differs in the methods.

Assuming offer.getOfferRows() returns List<OfferRow>, then:

public String getAllDangerousProductsName(Offer offer, Predicate<OfferRow> predicate) {
    return offer.getOfferRows().stream()
            .filter(predicate)
            .map(row -> row.getItemInformation().getOfferTexts().getName())
            .collect(Collectors.joining(","));
}

Usage becomes fairly simple:

// using lambda expression
String str1 = getAllDangerousProductsName(offer, row -> row.isDangerousGood());
String str2 = getAllDangerousProductsName(offer, row -> row.isBulkyGood());
// using method reference
String str1 = getAllDangerousProductsName(offer, OfferRow::isDangerousGood);
String str2 = getAllDangerousProductsName(offer, OfferRow::isBulkyGood);

推荐阅读