java - 使用流 api 更新现有函数
问题描述
我有以下方法,我想使用流重写。
我正在考虑编写一个方法并调用它,stream().forEach()
但不确定如何映射返回。
List<Student> students = new ArrayList<>();
if(myService.getData()!=null){
for(Person person: myService.getData().getPersons()) {
Student student = new Student();
student.setGender(person.getSex());
student.setGpa(person.getScore);
students.add(student);
}
}
解决方案
您可以使用Optional然后使用构造函数创建Student
对象
public Student(String sex, Integer score) {
this.sex = sex;
this.score = score;
}
然后流式传输Person
列表以创建Student
List<Student> students = Optional.ofNullable(myService.getData())
.map(data->data.getPersons().stream().map(per->new Student(per.getSex(),per.getScore())).collect(Collectors.toList())
.orElse(Collections.emptyList();
您还可以添加空检查getPersons()
List<Student> students = Optional.ofNullable(myService.getData())
.filter(data->data.getPersons()!=null)
.map(data->data.getPersons().stream().map(per->new Student(per.getSex(),per.getScore())).collect(Collectors.toList())
.orElse(Collections.emptyList();
推荐阅读
- c# - 如何获得正确的时间
- macos - gcloud 在我的本地(OSX)开发人员机器上每小时做什么
- postgresql - 一次由多个用户在 postgres 中恢复 postgres 数据库
- php - 在单个查询中从多个表中获取数据
- python - date2num 是否仍在更新的 Mplfinance 解释器中?
- jquery - 使用 Jquery 删除测试字符串中第一个数字之前的文本
- apache-kafka - 安装 Kafka 2.7.0 并出现此错误:无法找到或加载主类 org.apache.zookeeper.server.quorum.QuorumPeerMain
- python - 自动修复vscode中python代码中的间距错误
- python - 如何解决 Python 中的“无法连接 'str' 和 'list' 对象”?
- python - 对于大约 250 000 个模型的对象,Django 是否应该变得如此缓慢?