All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kiwiproject.collect.KiwiStreams Maven / Gradle / Ivy

Go to download

Kiwi is a utility library. We really like Google's Guava, and also use Apache Commons. But if they don't have something we need, and we think it is useful, this is where we put it.

There is a newer version: 4.5.2
Show newest version
package org.kiwiproject.collect;

import lombok.experimental.UtilityClass;

import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * Utilities related to Streams that are not already in the JDKs {@link java.util.stream.Stream}
 * or Guava's {@link com.google.common.collect.Streams}.
 */
@UtilityClass
public final class KiwiStreams {

    /**
     * Find the first object having the given {@code typeToFind} in a stream of objects.
     *
     * @param stream        the stream of objects of some (unknown) type
     * @param typeToFind    the class of the object to find
     * @param            the type token of the type we want to find
     * @return an Optional containing the first object of the given type, or empty
     */
    public static  Optional findFirst(Stream stream, Class typeToFind) {
        return findFirst(stream, typeToFind, obj -> true);
    }

    /**
     * Find the first object having the given {@code typeToFind} and matching the supplied
     * predicate in a stream of objects.
     *
     * @param stream        the stream of objects of some (unknown) type
     * @param typeToFind    the class of the object to find
     * @param predicate     the condition that must be satisfied for a match to occur
     * @param            the type token of the type we want to find
     * @return an Optional containing the first object of the given type, or empty
     */
    public static  Optional findFirst(Stream stream, Class typeToFind, Predicate predicate) {
        return stream
                .filter(obj -> typeToFind.isAssignableFrom(obj.getClass()))
                .map(typeToFind::cast)
                .filter(predicate)
                .findFirst();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy