我可以用 Java 中的 List 以哪种方式写出 for 循环?

是否可以使用 Lambda 表达式或更好的方法来写下 for 循环?


public TaskDTO convertToDTO(Task task) {

    for (int i = 0; i < task.getPrecedingTasks().size(); i++)

        this.precedingTasks.add(task.getPrecedingTasks().get(i).getName());

}


慕码人8056858
浏览 152回答 3
3回答

翻翻过去那场雪

您的解决方案很好:task.getPrecedingTasks().stream().map(Task::getName).forEach(this.precedingTasks::add);但由于您只是检索 , 的一部分Task,map然后collect作为列表:this.precedingTasks&nbsp;=&nbsp;task.getPrecedingTasks().stream().map(Task::getName).collect(Collectors.toList());是不是更简单易懂?因为stream这里是做映射/转换然后收集。而且通过这种方式,您不需要对this.precedingTasksas进行初始化this.precedingTasks&nbsp;=&nbsp;new&nbsp;ArrayList<>();&nbsp;//&nbsp;to&nbsp;ensure&nbsp;it's&nbsp;not&nbsp;null;无论如何,这里只是个人喜好。

jeck猫

这是一个完整的例子,我把 System.out.println ... 你应该使用 this.precedingTasks.addAll( ...import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;public class Main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Task t1 = new Task("myTask", Arrays.asList(new Task("innerTask1"), new Task("innerTask2")));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(t1.precedingTasks.stream().map(Task::getName).collect(Collectors.toList()));&nbsp; &nbsp; }&nbsp; &nbsp; static class Task {&nbsp; &nbsp; &nbsp; &nbsp; private String name;&nbsp; &nbsp; &nbsp; &nbsp; private List<Task> precedingTasks = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; public Task(String name) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public Task(String name, List<Task> precedingTasks) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.precedingTasks = precedingTasks;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public String getName() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return name;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public List<Task> getPrecedingTasks() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return precedingTasks;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出是[innerTask1, innerTask2]

长风秋雁

我在我的案例中找到了正确的解决方案:task.getPrecedingTasks().stream().map(Task::getName).forEach(this.precedingTasks::add);谢谢,提示:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java