Cannot convert java.util.Optional with stream

后端 未结 3 1266
-上瘾入骨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:02

    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 then use isPresent to process only the Optional objects that contain Student

    Arrays.stream

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

    IntStream.of

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

    In current approach your are returning List>

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

提交回复
热议问题