java - Functional programming for ForLoop
问题描述
I am new to functional programming and needs some sort of guidance of writing the below piece of code using java
public List<sampleEntity> sampleLetter(List<String> sampleIds) {
List<sampleEntity> lstsampleEntity = new ArrayList<>();
//Wanted to have the below for loop written using functional programming
for (String sampleId : sampleIds) {
lstsampleEntity.add(sampleLetter(sampleId));
}
return lstsampleEntity;
}
解决方案
return sampleIds.stream()
.map(s -> sampleLetter(s))
.collect(Collectors.toList());
请注意,lambda 可以写为方法引用(this::sampleLetter
或TheClass::sampleLetter
);你没有显示重载的方法声明,所以我只使用了在任何一种情况下都有效的 lambda。
推荐阅读
- python - 用户选项和验证
- python - 执行一个函数可以防止 tkinter 窗口出现
- mysql - 显示具有其他属性的组中的第一个和最后一个 mysql 记录
- python-3.x - 无法使用 selenium 从网站中定位元素
- php - Laravel 8 没有从包“\Conner\Tagging\Taggable;”中找到“标签”
- c - 时间复杂度会根据参数变化吗?
- reactjs - 开玩笑的期望语句不会等待承诺得到解决
- strapi - 如何在strapi中使用根路由(/)作为/admin
- google-sheets - 从 vlookup 检查 Google 表格中的文本而不破坏公式、文本换行或将列宽更改为“适合数据”?
- javafx - 结束时如何重置 JavaFX 媒体播放器?