Stream.findFirst different than Optional.of?

后端 未结 5 1203
旧时难觅i
旧时难觅i 2021-02-18 19:13

Let\'s say I have two classes and two methods:

class Scratch {
    private class A{}
    private class B extends A{}

    public Optional getItems(List&         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-18 20:08

    The issue you have is with inheritance for generics. Optional< B > doesn't extend Optional< A >, so it can't be returned as such.

    I'd imagine that something like this:

    public Optional getItems( List items){
        return items.stream()
            .map(s -> new B())
            .findFirst();
    }
    

    Or:

    public Optional getItems( List items){
        return items.stream()
            .map(s -> new B())
            .findFirst();
    }
    

    Would work fine, depending on your needs.

    Edit: escaping some characters

提交回复
热议问题