Java Stream Operation ofType(Stream stream, Class type)

Here you can find the source of ofType(Stream stream, Class type)

Description

Keep only those elements in a stream that are of a given type.

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
public static <T, U> Stream<U> ofType(Stream<T> stream, Class<U> type) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.stream.Stream;

public class Main {
    /**/*ww  w.j  a  v  a  2  s.c o  m*/
     * Keep only those elements in a stream that are of a given type.
     * 
     * 
     * assertThat(Arrays.asList(1, 2, 3), 
     *      equalTo( StreamUtils.ofType(Stream.of(1, "a", 2, "b", 3,Integer.class));
     * 
     */
    @SuppressWarnings("unchecked")
    public static <T, U> Stream<U> ofType(Stream<T> stream, Class<U> type) {
        return stream.filter(type::isInstance).map(t -> (U) t);
    }
}

Related

  1. maximum(final Stream stream)
  2. maxLong(Stream stream)
  3. maxStringLength(Stream stringStream)
  4. mkString(Stream items, String prefix, String delimiter, String suffix)
  5. nullableStreamOf(Collection nullableCollection)
  6. opt2stream(Optional opt)
  7. optionalToStream(final Optional optional)
  8. optionalToStream(Optional optional)
  9. orStream(Stream> stream)