Is it possible to cast a Stream in Java 8?

后端 未结 4 1936
迷失自我
迷失自我 2020-12-02 08:26

Is it possible to cast a stream in Java 8? Say I have a list of objects, I can do something like this to filter out all the additional objects:

Stream.of(obj         


        
4条回答
  •  孤街浪徒
    2020-12-02 08:49

    I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

    Stream.of(objects)
        .filter(c -> c instanceof Client)
        .map(c -> (Client) c)
        .map(Client::getID)
        .forEach(System.out::println);
    

    or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

    Stream.of(objects)
        .filter(Client.class::isInstance)
        .map(Client.class::cast)
        .map(Client::getID)
        .forEach(System.out::println);
    

提交回复
热议问题