Cannot convert java.util.Optional with stream

后端 未结 3 1269
-上瘾入骨i
-上瘾入骨i 2021-01-26 11:51

I\'m trying to use stream in java, i had a student class:

@Entity
@Data @AllArgsConstructor @NoArgsConstructor
public class Student {
    @Id @GeneratedValue(str         


        
3条回答
  •  后悔当初
    2021-01-26 12:04

    Thank you all, your answers helped me to derive a solution:

    List students= Arrays.stream(empIds)
                    .mapToObj(id->
                       studentRepository.findById(id).get())
                    .collect(Collectors.toList());
    

    And the response of deadpool is great also, we have to add .map(Optional::get) to get the stream of student because studentRepository::findById return stream of optioanl that's why the error.

    List students= Arrays.stream(empIds)
                    .mapToObj(studentRepository::findById)
                   // .filter(Optional::isPresent)
                    .map(Optional::get)
                    .collect(Collectors.toList());
    

提交回复
热议问题