在Java 8中的forEach循环或流操作中:

huangapple go评论78阅读模式
英文:

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&lt;Employee&gt; employeeList = new ArrayList&lt;&gt;();
List&lt;EmployeeDetails&gt; 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&lt;Employee&gt; employeeList = getEmployees().stream()
  .flatMap(e -&gt; convertData(e).stream())
  .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年10月28日 05:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64563195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定