【问题标题】:For of to forEach -> lambda expressionFor of to forEach -> lambda 表达式
【发布时间】:2019-08-04 17:15:50
【问题描述】:

我的 java 代码中有一个“for of”,我尝试使用 lambda 表达式转换为“for each”。

for (Bicycle element : bicycleList) {
    txtOutput.append("Model:" + element.getModel() + "\n"); 
}

我已经尝试过这样做:

bicycleList.forEach(txtOutput.append -> ("Model:" + bicycle.getModel() + "\n"));

谁能帮帮我?

【问题讨论】:

标签: java for-loop arraylist lambda foreach


【解决方案1】:

bicycleList.forEach(element -> txtOutput.append("Model:" + element.getModel() + "\n"));

【讨论】:

    【解决方案2】:

    您也可以将流用作:

    String txtOutput = bicycleList.stream()
            .map(element -> "Model:" + element.getModel() + "\n")
            .collect(Collectors.joining("", "", ""));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多