java - 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?
解决方案
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);
推荐阅读
- woocommerce - 试图弄清楚如何从 WooCommerce 购物车中删除特定项目,而不是一次删除一个
- c# - 应用程序启动时如何选择由 HierarchicalDataTemplate 填充的 TreeViewItem?
- html - RMarkdown 标签集中包含“未定义”标签?
- airflow - 将 xcom 从 PythonVirtualenvOperator 推送到 PythonBranchOperator
- laravel - Laravel 队列:工作不能快速处理工作
- flutter - 我在颤振 Web 应用程序中使用 country_code_picker 2.0.1。初始选择不起作用
- python - 在出现关键短语python后使用正则表达式删除句子
- stata - 如何获取数据集的非连续进入和退出日期?
- django - 如何将我的 django 模型插入到 postgres?
- youtube - 所有视频的 Youtube 统计数据