如何转换';每个';循环到Java 8';溪流';
如何将迭代循环“to”转换为流o java8在您的体内包含一个搜索结果的方法如何转换';每个';循环到Java 8';溪流';,java,java-stream,Java,Java Stream,如何将迭代循环“to”转换为流o java8在您的体内包含一个搜索结果的方法 for(VagasRemanecentesResponse turaluAUnic : turaluListaA){ listAlunoCursoResponse = alunoCursoBusiness.findByCodInstAndRgmAlun(inst, turaluAUnic.getRgmAluno()); if (listAlunoCursoResponse.size() &
for(VagasRemanecentesResponse turaluAUnic : turaluListaA){
listAlunoCursoResponse = alunoCursoBusiness.findByCodInstAndRgmAlun(inst, turaluAUnic.getRgmAluno());
if (listAlunoCursoResponse.size() > 0) {
aluCurListaB.add(new VagasRemanecentesResponse(turaluAUnic, listAlunoCursoResponse));
}
}
或者是一个更简单的例子,表示问题的一部分,比如不使用“for”
for(Student student: students ) {
listAlunoCursoResponse.addAll(findByid(student.getId));
}
假设
findByid
返回一个对象,而不是集合(否则必须使用flatMap
):
虽然这当然是可能的,但您的代码肯定会更加清晰。基于流的版本需要同时跟踪turaluAUnic
元素和相应的listAlunoCursoResponse
。我查看了映射和流如何工作的示例,但没有找到在迭代循环中调用方法的选项。如何做到这一点?例如,在一个简单的示例中,我有一个学生标识符列表,并对一个方法进行了多次调用,在该方法中,我传递了一个学生标识符以获取填充的对象。它类似于:students.foreach(student->listAlunoCursoResponse.addAll(findByid(student.getId)))但是正如VGR所说的那样,仅仅比较后一种代码的流版本是毫无意义的。@miljon看起来像List List=students.stream().flatMap(student->findByid(student.getId.stream()).collect(Collectors.toList())
listAlunoCursoResponse.addAll(students.stream()
.map(student -> findByid(student.getId))
.collect(Collectors.toList()));