Java Stream Operation findLastOf(Stream stream)

Here you can find the source of findLastOf(Stream stream)

Description

Based on http://stackoverflow.com/questions/27547519/most-efficient-way-to-get-the-last-element-of-a-stream

License

Open Source License

Declaration

public static <T> Optional<T> findLastOf(Stream<T> stream) 

Method Source Code


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

import java.util.Iterator;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;

public class Main {
    /**/*  w w  w  . j av  a  2s  .  c  o m*/
     * Based on http://stackoverflow.com/questions/27547519/most-efficient-way-to-get-the-last-element-of-a-stream
     */
    public static <T> Optional<T> findLastOf(Stream<T> 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) {
                    split = part;
                    break;
                }
            }
        }

        T value = null;
        for (Iterator<T> it = traverse(split); it.hasNext();) {
            value = it.next();
        }

        return Optional.ofNullable(value);
    }

    private static <T> Iterator<T> traverse(Spliterator<T> sp) {
        Spliterator<T> prev = sp.trySplit();

        if (prev == null) {
            return Spliterators.iterator(sp);
        }

        Iterator<T> it = traverse(sp);

        if (it != null && it.hasNext()) {
            return it;
        }

        return traverse(prev);
    }
}

Related

  1. equals(Stream first, Stream second)
  2. factorStream(long number)
  3. filterInstances(Stream stream, Class clazz)
  4. filterType(Stream stream, Class type)
  5. findLast(Stream s)
  6. findStreamAmongst(Class clazz, Collection instances)
  7. firstValue(Stream stream)
  8. flatOptionals(Stream> list)
  9. flattenFeatureStreamToMap( Stream>>> stream)