Is it possible to cast a Stream in Java 8?

后端 未结 4 1930
迷失自我
迷失自我 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:42

    Late to the party, but I think it is a useful answer.

    flatMap would be the shortest way to do it.

    Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())
    

    If o is a Client then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream.

提交回复
热议问题