Java Utililty Methods Stream Operation

List of utility methods to do Stream Operation

Description

The list of methods to do Stream Operation are organized into topic(s).

Method

booleancontainsOnly(Stream stream, long size)
Helper which lazily checks if a Stream contains the number specified WARNING: This consumes the stream rendering it unusable afterwards
long count = 0L;
Iterator it = stream.iterator();
while (it.hasNext()) {
    it.next();
    if (++count > size)
        return false;
return size == count;
...
StreamcreateStream(final Iterator iterator)
Creates a stream based on the provided iterator.
requireNonNull(iterator, "Iterator must not be null");
return StreamSupport.stream(Spliterators.spliterator(iterator, 0L, 0), false);
booleanendsWith(Stream stream, Iterable iterable)
ends With
Iterator<T> it = iterable.iterator();
List<T> compare1 = new ArrayList<>();
while (it.hasNext()) {
    compare1.add(it.next());
LinkedList<T> list = new LinkedList<>();
stream.forEach(v -> {
    list.add(v);
...
StreamenumerationAsStream(Enumeration e)
enumeration As Stream
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(new Iterator<T>() {
    public T next() {
        return e.nextElement();
    public boolean hasNext() {
        return e.hasMoreElements();
}, Spliterator.ORDERED), false);
...
booleanequals(Stream first, Stream second)
equals
Iterator<?> firstIterator = first.iterator();
Iterator<?> secondIterator = second.iterator();
while (firstIterator.hasNext() && secondIterator.hasNext()) {
    if (!Objects.equals(firstIterator.next(), secondIterator.next())) {
        return false;
return !firstIterator.hasNext() && !secondIterator.hasNext();
...
LongStreamfactorStream(long number)
factor Stream
return LongStream.rangeClosed(2, (long) Math.sqrt(number)).filter(f -> number % f == 0)
        .flatMap(f -> LongStream.of(f, number / f)).sorted();
StreamfilterInstances(Stream stream, Class clazz)
filter Instances
return stream.filter(clazz::isInstance);
StreamfilterType(Stream stream, Class type)
filter Type
return (Stream<Sub>) stream.filter(it -> type.isInstance(it));
OptionalfindLast(Stream s)
find Last
return Optional.ofNullable(s.reduce(null, (p, c) -> c));
OptionalfindLastOf(Stream stream)
Based on http://stackoverflow.com/questions/27547519/most-efficient-way-to-get-the-last-element-of-a-stream
Spliterator<T> split = stream.spliterator();
if (split.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED)) {
    while (true) {
        Spliterator<T> part = split.trySplit();
        if (part == null) {
            break;
        if (split.getExactSizeIfKnown() == 0) {
...