Cannot convert java.util.Optional<class> with stream

…衆ロ難τιáo~ 提交于 2021-01-20 12:43:35

问题


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

@Entity
@Data @AllArgsConstructor @NoArgsConstructor
public class Student {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

I added some students:

Stream.of("John","Sophie","emilia").forEach(s->{
            studentRepository.save(new Student(s));
        });

The probleme is in the below code:

int[] empIds = { 1, 2, 3 };
        List<Student> students= Stream.of(empIds)
                .map(studentRepository::findById).collect(Collectors.toList());

i got this error: bad return type in method reference:cannot convert java.util.Optional to R. My IDE underline studentRepository::findById. Many thanks.


回答1:


The First problem is Stream.of will create an stream of int arrays instead of stream of Integer

For Example

Stream.of(empIds).forEach(System.out::println);      //[I@7c3e4b1a
IntStream.of(empIds).forEach(System.out::println);   //1 2 3

So use IntStream.of or Arrays.stream()

If findById() is returning Optional<Student> then use isPresent to process only the Optional objects that contain Student

Arrays.stream

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

IntStream.of

List<Student> students= IntStream.of(empIds)
            .mapToObj(studentRepository::findById)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .collect(Collectors.toList());

In current approach your are returning List<Optional<Student>>

List<Optional<Student>> students= IntStream.of(empIds)
            .map(studentRepository::findById).collect(Collectors.toList());



回答2:


To be able to use it in map() function, StudentRepository.findById() needs to return Optional<Student> instead of just Student.




回答3:


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

List<Student> 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<Student> students= Arrays.stream(empIds)
                .mapToObj(studentRepository::findById)
               // .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());


来源:https://stackoverflow.com/questions/56280034/cannot-convert-java-util-optionalclass-with-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!