英文:
forEach loop in java8 or streams
问题
我打算使用Java 8来编写以下代码。
List<Employee> employeeList = new ArrayList<>();
List<EmployeeDetails> emps = getEmployees();
if (emps.size() != 0) {
for (EmployeeDetails e : emps) {
employeeList.addAll(convertData(e));
}
}
采用哪种方法比较好?我需要使用lambda表达式还是流(Streams)?
英文:
I was looking to write the below code using Java 8.
List<Employee> employeeList = new ArrayList<>();
List<EmployeeDetails> emps = getEmployees();
if (emps.size() != 0) {
for (EmployeeDetails e : emps) {
employeeList.addAll(convertData(e));
}
}
What would be a good approach? Do I need to use lambda or streams?
答案1
得分: 2
你所编写的代码,明确地说,是“完全正常”的,但如果你想要使用流重写它,它会看起来像这样:
List<Employee> employeeList = getEmployees().stream()
.flatMap(e -> convertData(e).stream())
.collect(Collectors.toList());
英文:
The code you've written, to be clear, is just fine, but if you wanted to rewrite it with streams, it would look like
List<Employee> employeeList = getEmployees().stream()
.flatMap(e -> convertData(e).stream())
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论