无法转换java.util.Optional< class>与流 [英] Cannot convert java.util.Optional<class> with stream

查看:154
本文介绍了无法转换java.util.Optional< class>与流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Java中使用流,我有一个学生班:

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;

我添加了一些学生:

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

问题在下面的代码中:

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

我收到此错误:方法参考中的错误返回类型:无法将java.util.Optional转换为R.我的IDE下划线为StudentRepository :: findById. 非常感谢.

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

推荐答案

第一个问题是Stream.of将创建int arrays流而不是Integer流

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

例如

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

因此请使用IntStream.ofArrays.stream()

如果findById()返回Optional<Student>,则使用isPresent仅处理包含Student

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());

在当前方法中,您将返回List<Optional<Student>>

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

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

这篇关于无法转换java.util.Optional&lt; class&gt;与流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆