Is it possible to cast a Stream in Java 8?

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

    Along the lines of ggovan's answer, I do this as follows:

    /**
     * Provides various high-order functions.
     */
    public final class F {
        /**
         * When the returned {@code Function} is passed as an argument to
         * {@link Stream#flatMap}, the result is a stream of instances of
         * {@code cls}.
         */
        public static  Function> instancesOf(Class cls) {
            return o -> cls.isInstance(o)
                    ? Stream.of(cls.cast(o))
                    : Stream.empty();
        }
    }
    

    Using this helper function:

    Stream.of(objects).flatMap(F.instancesOf(Client.class))
            .map(Client::getId)
            .forEach(System.out::println);
    

提交回复
热议问题