    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3;
    018
    019import java.util.ArrayList;
    020import java.util.Collection;
    021import java.util.Collections;
    022import java.util.List;
    023import java.util.Set;
    024import java.util.function.BiConsumer;
    025import java.util.function.BinaryOperator;
    026import java.util.function.Consumer;
    027import java.util.function.Function;
    028import java.util.function.Predicate;
    029import java.util.function.Supplier;
    030import java.util.stream.Collector;
    031import java.util.stream.Collectors;
    032import java.util.stream.Stream;
    033
    034import org.apache.commons.lang3.Functions.FailableConsumer;
    035import org.apache.commons.lang3.Functions.FailableFunction;
    036import org.apache.commons.lang3.Functions.FailablePredicate;
    037
    038/**
    039 * Provides utility functions, and classes for working with the
    040 * {@code java.util.stream} package, or more generally, with Java 8 lambdas. More
    041 * specifically, it attempts to address the fact that lambdas are supposed
    042 * not to throw Exceptions, at least not checked Exceptions, AKA instances
    043 * of {@link Exception}. This enforces the use of constructs like
    044 * <pre>{@code
    045 *     Consumer<java.lang.reflect.Method> consumer = m -> {
    046 *         try {
    047 *             m.invoke(o, args);
    048 *         } catch (Throwable t) {
    049 *             throw Functions.rethrow(t);
    050 *         }
    051 *    };
    052 *    stream.forEach(consumer);
    053 * }</pre>
    054 * Using a {@link FailableStream}, this can be rewritten as follows:
    055 * <pre>{@code
    056 *     Streams.failable(stream).forEach(m -> m.invoke(o, args));
    057 * }</pre>
    058 * Obviously, the second version is much more concise and the spirit of
    059 * Lambda expressions is met better than in the first version.
    060 *
    061 * @see Stream
    062 * @see Functions
    063 * @since 3.10
    064 * @deprecated Use {@link org.apache.commons.lang3.stream.Streams}.
    065 */
    066@Deprecated
    067public class Streams {
    068
    069    /**
    070     * A Collector type for arrays.
    071     *
    072     * @param <O> The array type.
    073     * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}.
    074     */
    075    @Deprecated
    076    public static class ArrayCollector<O> implements Collector<O, List<O>, O[]> {
    077        private static final Set<Characteristics> characteristics = Collections.emptySet();
    078        private final Class<O> elementType;
    079
    080        /**
    081         * Constructs a new instance for the given element type.
    082         *
    083         * @param elementType The element type.
    084         */
    085        public ArrayCollector(final Class<O> elementType) {
    086            this.elementType = elementType;
    087        }
    088
    089        @Override
    090        public BiConsumer<List<O>, O> accumulator() {
    091            return List::add;
    092        }
    093
    094        @Override
    095        public Set<Characteristics> characteristics() {
    096            return characteristics;
    097        }
    098
    099        @Override
    100        public BinaryOperator<List<O>> combiner() {
    101            return (left, right) -> {
    102                left.addAll(right);
    103                return left;
    104            };
    105        }
    106
    107        @Override
    108        public Function<List<O>, O[]> finisher() {
    109            return list -> list.toArray(ArrayUtils.newInstance(elementType, list.size()));
    110        }
    111
    112        @Override
    113        public Supplier<List<O>> supplier() {
    114            return ArrayList::new;
    115        }
    116    }
    117
    118    /**
    119     * A reduced, and simplified version of a {@link Stream} with
    120     * failable method signatures.
    121     * @param <O> The streams element type.
    122     * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.FailableStream}.
    123     */
    124    @Deprecated
    125    public static class FailableStream<O> {
    126
    127        private Stream<O> stream;
    128        private boolean terminated;
    129
    130        /**
    131         * Constructs a new instance with the given {@code stream}.
    132         * @param stream The stream.
    133         */
    134        public FailableStream(final Stream<O> stream) {
    135            this.stream = stream;
    136        }
    137
    138        /**
    139         * Returns whether all elements of this stream match the provided predicate.
    140         * May not evaluate the predicate on all elements if not necessary for
    141         * determining the result.  If the stream is empty then {@code true} is
    142         * returned and the predicate is not evaluated.
    143         *
    144         * <p>
    145         * This is a short-circuiting terminal operation.
    146         * </p>
    147         *
    148         * <p>
    149         * Note
    150         * This method evaluates the <em>universal quantification</em> of the
    151         * predicate over the elements of the stream (for all x P(x)).  If the
    152         * stream is empty, the quantification is said to be <em>vacuously
    153         * satisfied</em> and is always {@code true} (regardless of P(x)).
    154         * </p>
    155         *
    156         * @param predicate A non-interfering, stateless predicate to apply to
    157         * elements of this stream.
    158         * @return {@code true} If either all elements of the stream match the
    159         * provided predicate or the stream is empty, otherwise {@code false}.
    160         */
    161        public boolean allMatch(final FailablePredicate<O, ?> predicate) {
    162            assertNotTerminated();
    163            return stream().allMatch(Functions.asPredicate(predicate));
    164        }
    165
    166        /**
    167         * Returns whether any elements of this stream match the provided
    168         * predicate.  May not evaluate the predicate on all elements if not
    169         * necessary for determining the result.  If the stream is empty then
    170         * {@code false} is returned and the predicate is not evaluated.
    171         *
    172         * <p>
    173         * This is a short-circuiting terminal operation.
    174         * </p>
    175         *
    176         * Note
    177         * This method evaluates the <em>existential quantification</em> of the
    178         * predicate over the elements of the stream (for some x P(x)).
    179         *
    180         * @param predicate A non-interfering, stateless predicate to apply to
    181         * elements of this stream.
    182         * @return {@code true} if any elements of the stream match the provided
    183         * predicate, otherwise {@code false}.
    184         */
    185        public boolean anyMatch(final FailablePredicate<O, ?> predicate) {
    186            assertNotTerminated();
    187            return stream().anyMatch(Functions.asPredicate(predicate));
    188        }
    189
    190        /**
    191         * Throws IllegalStateException if this stream is already terminated.
    192         *
    193         * @throws IllegalStateException if this stream is already terminated.
    194         */
    195        protected void assertNotTerminated() {
    196            if (terminated) {
    197                throw new IllegalStateException("This stream is already terminated.");
    198            }
    199        }
    200
    201        /**
    202         * Performs a mutable reduction operation on the elements of this stream using a
    203         * {@link Collector}.  A {@link Collector}
    204         * encapsulates the functions used as arguments to
    205         * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of
    206         * collection strategies and composition of collect operations such as
    207         * multiple-level grouping or partitioning.
    208         *
    209         * <p>
    210         * If the underlying stream is parallel, and the {@link Collector}
    211         * is concurrent, and either the stream is unordered or the collector is
    212         * unordered, then a concurrent reduction will be performed
    213         * (see {@link Collector} for details on concurrent reduction.)
    214         * </p>
    215         *
    216         * <p>
    217         * This is an intermediate operation.
    218         * </p>
    219         *
    220         * <p>
    221         * When executed in parallel, multiple intermediate results may be
    222         * instantiated, populated, and merged so as to maintain isolation of
    223         * mutable data structures.  Therefore, even when executed in parallel
    224         * with non-thread-safe data structures (such as {@link ArrayList}), no
    225         * additional synchronization is needed for a parallel reduction.
    226         * </p>
    227         * <p>
    228         * Note
    229         * The following will accumulate strings into an ArrayList:
    230         * </p>
    231         * <pre>{@code
    232         *     List<String> asList = stringStream.collect(Collectors.toList());
    233         * }</pre>
    234         *
    235         * <p>
    236         * The following will classify {@code Person} objects by city:
    237         * </p>
    238         * <pre>{@code
    239         *     Map<String, List<Person>> peopleByCity
    240         *         = personStream.collect(Collectors.groupingBy(Person::getCity));
    241         * }</pre>
    242         *
    243         * <p>
    244         * The following will classify {@code Person} objects by state and city,
    245         * cascading two {@link Collector}s together:
    246         * </p>
    247         * <pre>{@code
    248         *     Map<String, Map<String, List<Person>>> peopleByStateAndCity
    249         *         = personStream.collect(Collectors.groupingBy(Person::getState,
    250         *                                                      Collectors.groupingBy(Person::getCity)));
    251         * }</pre>
    252         *
    253         * @param <R> the type of the result.
    254         * @param <A> the intermediate accumulation type of the {@link Collector}.
    255         * @param collector the {@link Collector} describing the reduction.
    256         * @return the result of the reduction.
    257         * @see #collect(Supplier, BiConsumer, BiConsumer)
    258         * @see Collectors
    259         */
    260        public <A, R> R collect(final Collector<? super O, A, R> collector) {
    261            makeTerminated();
    262            return stream().collect(collector);
    263        }
    264
    265        /**
    266         * Performs a mutable reduction operation on the elements of this FailableStream.
    267         * A mutable reduction is one in which the reduced value is a mutable result
    268         * container, such as an {@link ArrayList}, and elements are incorporated by updating
    269         * the state of the result rather than by replacing the result. This produces a result equivalent to:
    270         * <pre>{@code
    271         *     R result = supplier.get();
    272         *     for (T element : this stream)
    273         *         accumulator.accept(result, element);
    274         *     return result;
    275         * }</pre>
    276         *
    277         * <p>
    278         * Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations
    279         * can be parallelized without requiring additional synchronization.
    280         * </p>
    281         *
    282         * <p>
    283         * This is an intermediate operation.
    284         * </p>
    285         *
    286         * <p>
    287         * Note There are many existing classes in the JDK whose signatures are
    288         * well-suited for use with method references as arguments to {@code collect()}.
    289         * For example, the following will accumulate strings into an {@link ArrayList}:
    290         * </p>
    291         * <pre>{@code
    292         *     List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add,
    293         *                                                ArrayList::addAll);
    294         * }</pre>
    295         *
    296         * <p>
    297         * The following will take a stream of strings and concatenates them into a
    298         * single string:
    299         * </p>
    300         * <pre>{@code
    301         *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
    302         *                                          StringBuilder::append)
    303         *                                 .toString();
    304         * }</pre>
    305         *
    306         * @param <R> type of the result.
    307         * @param <A> Type of the accumulator.
    308         * @param supplier a function that creates a new result container. For a
    309         *                 parallel execution, this function may be called
    310         *                 multiple times and must return a fresh value each time.
    311         * @param accumulator An associative, non-interfering, stateless function for
    312         *   incorporating an additional element into a result.
    313         * @param combiner An associative, non-interfering, stateless
    314         *   function for combining two values, which must be compatible with the
    315         *   accumulator function.
    316         * @return The result of the reduction.
    317         */
    318        public <A, R> R collect(final Supplier<R> supplier, final BiConsumer<R, ? super O> accumulator, final BiConsumer<R, R> combiner) {
    319            makeTerminated();
    320            return stream().collect(supplier, accumulator, combiner);
    321        }
    322
    323        /**
    324         * Returns a FailableStream consisting of the elements of this stream that match
    325         * the given FailablePredicate.
    326         *
    327         * <p>
    328         * This is an intermediate operation.
    329         * </p>
    330         *
    331         * @param predicate a non-interfering, stateless predicate to apply to each
    332         * element to determine if it should be included.
    333         * @return the new stream.
    334         */
    335        public FailableStream<O> filter(final FailablePredicate<O, ?> predicate) {
    336            assertNotTerminated();
    337            stream = stream.filter(Functions.asPredicate(predicate));
    338            return this;
    339        }
    340
    341        /**
    342         * Performs an action for each element of this stream.
    343         *
    344         * <p>
    345         * This is an intermediate operation.
    346         * </p>
    347         *
    348         * <p>
    349         * The behavior of this operation is explicitly nondeterministic.
    350         * For parallel stream pipelines, this operation does <em>not</em>
    351         * guarantee to respect the encounter order of the stream, as doing so
    352         * would sacrifice the benefit of parallelism.  For any given element, the
    353         * action may be performed at whatever time and in whatever thread the
    354         * library chooses.  If the action accesses shared state, it is
    355         * responsible for providing the required synchronization.
    356         * </p>
    357         *
    358         * @param action a non-interfering action to perform on the elements.
    359         */
    360        public void forEach(final FailableConsumer<O, ?> action) {
    361            makeTerminated();
    362            stream().forEach(Functions.asConsumer(action));
    363        }
    364
    365        /**
    366         * Marks this stream as terminated.
    367         *
    368         * @throws IllegalStateException if this stream is already terminated.
    369         */
    370        protected void makeTerminated() {
    371            assertNotTerminated();
    372            terminated = true;
    373        }
    374
    375        /**
    376         * Returns a stream consisting of the results of applying the given
    377         * function to the elements of this stream.
    378         *
    379         * <p>
    380         * This is an intermediate operation.
    381         * </p>
    382         *
    383         * @param <R> The element type of the new stream.
    384         * @param mapper A non-interfering, stateless function to apply to each element.
    385         * @return the new stream.
    386         */
    387        public <R> FailableStream<R> map(final FailableFunction<O, R, ?> mapper) {
    388            assertNotTerminated();
    389            return new FailableStream<>(stream.map(Functions.asFunction(mapper)));
    390        }
    391
    392        /**
    393         * Performs a reduction on the elements of this stream, using the provided
    394         * identity value and an associative accumulation function, and returns
    395         * the reduced value.  This is equivalent to:
    396         * <pre>{@code
    397         *     T result = identity;
    398         *     for (T element : this stream)
    399         *         result = accumulator.apply(result, element)
    400         *     return result;
    401         * }</pre>
    402         *
    403         * but is not constrained to execute sequentially.
    404         *
    405         * <p>
    406         * The {@code identity} value must be an identity for the accumulator
    407         * function. This means that for all {@code t},
    408         * {@code accumulator.apply(identity, t)} is equal to {@code t}.
    409         * The {@code accumulator} function must be an associative function.
    410         * </p>
    411         *
    412         * <p>
    413         * This is an intermediate operation.
    414         * </p>
    415         *
    416         * Note Sum, min, max, average, and string concatenation are all special
    417         * cases of reduction. Summing a stream of numbers can be expressed as:
    418         *
    419         * <pre>{@code
    420         *     Integer sum = integers.reduce(0, (a, b) -> a+b);
    421         * }</pre>
    422         *
    423         * or:
    424         *
    425         * <pre>{@code
    426         *     Integer sum = integers.reduce(0, Integer::sum);
    427         * }</pre>
    428         *
    429         * <p>
    430         * While this may seem a more roundabout way to perform an aggregation
    431         * compared to simply mutating a running total in a loop, reduction
    432         * operations parallelize more gracefully, without needing additional
    433         * synchronization and with greatly reduced risk of data races.
    434         * </p>
    435         *
    436         * @param identity the identity value for the accumulating function.
    437         * @param accumulator an associative, non-interfering, stateless
    438         *                    function for combining two values.
    439         * @return the result of the reduction.
    440         */
    441        public O reduce(final O identity, final BinaryOperator<O> accumulator) {
    442            makeTerminated();
    443            return stream().reduce(identity, accumulator);
    444        }
    445
    446        /**
    447         * Converts the FailableStream into an equivalent stream.
    448         * @return A stream, which will return the same elements, which this FailableStream would return.
    449         */
    450        public Stream<O> stream() {
    451            return stream;
    452        }
    453    }
    454
    455    /**
    456     * Converts the given {@link Collection} into a {@link FailableStream}.
    457     * This is basically a simplified, reduced version of the {@link Stream}
    458     * class, with the same underlying element stream, except that failable
    459     * objects, like {@link FailablePredicate}, {@link FailableFunction}, or
    460     * {@link FailableConsumer} may be applied, instead of
    461     * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is
    462     * to rewrite a code snippet like this:
    463     * <pre>{@code
    464     *     final List<O> list;
    465     *     final Method m;
    466     *     final Function<O,String> mapper = (o) -> {
    467     *         try {
    468     *             return (String) m.invoke(o);
    469     *         } catch (Throwable t) {
    470     *             throw Functions.rethrow(t);
    471     *         }
    472     *     };
    473     *     final List<String> strList = list.stream()
    474     *         .map(mapper).collect(Collectors.toList());
    475     *  }</pre>
    476     *  as follows:
    477     *  <pre>{@code
    478     *     final List<O> list;
    479     *     final Method m;
    480     *     final List<String> strList = Functions.stream(list.stream())
    481     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
    482     *  }</pre>
    483     *  While the second version may not be <em>quite</em> as
    484     *  efficient (because it depends on the creation of additional,
    485     *  intermediate objects, of type FailableStream), it is much more
    486     *  concise, and readable, and meets the spirit of Lambdas better
    487     *  than the first version.
    488     * @param <O> The streams element type.
    489     * @param stream The stream, which is being converted.
    490     * @return The {@link FailableStream}, which has been created by
    491     *   converting the stream.
    492     */
    493    public static <O> FailableStream<O> stream(final Collection<O> stream) {
    494        return stream(stream.stream());
    495    }
    496
    497    /**
    498     * Converts the given {@link Stream stream} into a {@link FailableStream}.
    499     * This is basically a simplified, reduced version of the {@link Stream}
    500     * class, with the same underlying element stream, except that failable
    501     * objects, like {@link FailablePredicate}, {@link FailableFunction}, or
    502     * {@link FailableConsumer} may be applied, instead of
    503     * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is
    504     * to rewrite a code snippet like this:
    505     * <pre>{@code
    506     *     final List<O> list;
    507     *     final Method m;
    508     *     final Function<O,String> mapper = (o) -> {
    509     *         try {
    510     *             return (String) m.invoke(o);
    511     *         } catch (Throwable t) {
    512     *             throw Functions.rethrow(t);
    513     *         }
    514     *     };
    515     *     final List<String> strList = list.stream()
    516     *         .map(mapper).collect(Collectors.toList());
    517     *  }</pre>
    518     *  as follows:
    519     *  <pre>{@code
    520     *     final List<O> list;
    521     *     final Method m;
    522     *     final List<String> strList = Functions.stream(list.stream())
    523     *         .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
    524     *  }</pre>
    525     *  While the second version may not be <em>quite</em> as
    526     *  efficient (because it depends on the creation of additional,
    527     *  intermediate objects, of type FailableStream), it is much more
    528     *  concise, and readable, and meets the spirit of Lambdas better
    529     *  than the first version.
    530     * @param <O> The streams element type.
    531     * @param stream The stream, which is being converted.
    532     * @return The {@link FailableStream}, which has been created by
    533     *   converting the stream.
    534     */
    535    public static <O> FailableStream<O> stream(final Stream<O> stream) {
    536        return new FailableStream<>(stream);
    537    }
    538
    539    /**
    540     * Returns a {@link Collector} that accumulates the input elements into a
    541     * new array.
    542     *
    543     * @param elementType Type of an element in the array.
    544     * @param <O> the type of the input elements.
    545     * @return a {@link Collector} which collects all the input elements into an
    546     * array, in encounter order.
    547     */
    548    public static <O> Collector<O, ?, O[]> toArray(final Class<O> elementType) {
    549        return new ArrayCollector<>(elementType);
    550    }
    551
    552    /**
    553     * Constructs a new instance.
    554     */
    555    public Streams() {
    556        // empty
    557    }
    558}