Top Description Inners Constructors Methods
org.apache.commons.lang3

public Class Streams

extends Object
Class Inheritance
Annotations
@Deprecated
Imports
java.util.ArrayList, .Collection, .Collections, .List, .Set, java.util.function.BiConsumer, .BinaryOperator, .Consumer, .Function, .Predicate, .Supplier, java.util.stream.Collector, .Collectors, .Stream, org.apache.commons.lang3.Functions.FailableConsumer, .Functions.FailableFunction, .Functions.FailablePredicate

Deprecated

Use org.apache.commons.lang3.stream.Streams.

Provides utility functions, and classes for working with the java.util.stream package, or more generally, with Java 8 lambdas. More specifically, it attempts to address the fact that lambdas are supposed not to throw Exceptions, at least not checked Exceptions, AKA instances of Exception. This enforces the use of constructs like
Consumer<java.lang.reflect.Method> consumer = m -> {
        try {
            m.invoke(o, args);
        } catch (Throwable t) {
            throw Functions.rethrow(t);
        }
   };
   stream.forEach(consumer);
Using a FailableStream, this can be rewritten as follows:
Streams.failable(stream).forEach(m -> m.invoke(o, args));
Obviously, the second version is much more concise and the spirit of Lambda expressions is met better than in the first version.
Since
3.10
See Also
Stream, Functions

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
Streams.ArrayCollector<
The array type.
O
>

A Collector type for arrays.
public static class
Streams.FailableStream<
The streams element type.
O
>

A reduced, and simplified version of a Stream with failable method signatures.

Constructor Summary

AccessConstructor and Description
public
Streams()

Constructs a new instance.

Method Summary

Modifier and TypeMethod and Description
public static <
The streams element type.
O
>
Streams.FailableStream<O>

Returns:

The FailableStream, which has been created by converting the stream.
stream
(final Collection<O>
The stream, which is being converted.
stream
)
References Deprecated Streams.FailableStream is deprecated or references (maybe indirectly) at least one deprecated element.

Converts the given Collection into a FailableStream.

public static <
The streams element type.
O
>
Streams.FailableStream<O>

Returns:

The FailableStream, which has been created by converting the stream.
stream
(final Stream<O>
The stream, which is being converted.
stream
)
References Deprecated Streams.FailableStream is deprecated or references (maybe indirectly) at least one deprecated element.

Converts the given stream into a FailableStream.

public static <
the type of the input elements.
O
>
Collector<O, ?, O[]>

Returns:

a Collector which collects all the input elements into an array, in encounter order.
toArray
(final Class<O>
Type of an element in the array.
elementType
)

Returns a Collector that accumulates the input elements into a new array.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

Streamsback to summary
public Streams()

Constructs a new instance.

Method Detail

streamback to summary
public static <O> Streams.FailableStream<O> stream(final Collection<O> stream)

References Deprecated

Streams.FailableStream is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Converts the given Collection into a FailableStream. This is basically a simplified, reduced version of the Stream class, with the same underlying element stream, except that failable objects, like FailablePredicate, FailableFunction, or FailableConsumer may be applied, instead of Predicate, Function, or Consumer. The idea is to rewrite a code snippet like this:

final List<O> list;
    final Method m;
    final Function<O,String> mapper = (o) -> {
        try {
            return (String) m.invoke(o);
        } catch (Throwable t) {
            throw Functions.rethrow(t);
        }
    };
    final List<String> strList = list.stream()
        .map(mapper).collect(Collectors.toList());
 
as follows:
final List<O> list;
    final Method m;
    final List<String> strList = Functions.stream(list.stream())
        .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
 
While the second version may not be quite as efficient (because it depends on the creation of additional, intermediate objects, of type FailableStream), it is much more concise, and readable, and meets the spirit of Lambdas better than the first version.
Parameters
<O>
The streams element type.
stream:Collection<O>

The stream, which is being converted.

Returns:Streams.FailableStream<O>

The FailableStream, which has been created by converting the stream.

streamback to summary
public static <O> Streams.FailableStream<O> stream(final Stream<O> stream)

References Deprecated

Streams.FailableStream is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Converts the given stream into a FailableStream. This is basically a simplified, reduced version of the Stream class, with the same underlying element stream, except that failable objects, like FailablePredicate, FailableFunction, or FailableConsumer may be applied, instead of Predicate, Function, or Consumer. The idea is to rewrite a code snippet like this:

final List<O> list;
    final Method m;
    final Function<O,String> mapper = (o) -> {
        try {
            return (String) m.invoke(o);
        } catch (Throwable t) {
            throw Functions.rethrow(t);
        }
    };
    final List<String> strList = list.stream()
        .map(mapper).collect(Collectors.toList());
 
as follows:
final List<O> list;
    final Method m;
    final List<String> strList = Functions.stream(list.stream())
        .map((o) -> (String) m.invoke(o)).collect(Collectors.toList());
 
While the second version may not be quite as efficient (because it depends on the creation of additional, intermediate objects, of type FailableStream), it is much more concise, and readable, and meets the spirit of Lambdas better than the first version.
Parameters
<O>
The streams element type.
stream:Stream<O>

The stream, which is being converted.

Returns:Streams.FailableStream<O>

The FailableStream, which has been created by converting the stream.

toArrayback to summary
public static <O> Collector<O, ?, O[]> toArray(final Class<O> elementType)

Returns a Collector that accumulates the input elements into a new array.

Parameters
<O>
the type of the input elements.
elementType:Class<O>

Type of an element in the array.

Returns:Collector<O, ?, O[]>

a Collector which collects all the input elements into an array, in encounter order.

org.apache.commons.lang3 back to summary

public Class Streams.ArrayCollector<O>

extends Object
implements Collector<O, List<O>, O[]>
Class Inheritance
All Implemented Interfaces
java.util.stream.Collector
Annotations
@Deprecated
Type Parameters
<O>
The array type.

Deprecated

Use org.apache.commons.lang3.stream.Streams.ArrayCollector.

A Collector type for arrays.

Field Summary

Modifier and TypeField and Description
private static final Set<Collector.Characteristics>
private final Class<O>

Constructor Summary

AccessConstructor and Description
public
ArrayCollector(final Class<O>
The element type.
elementType
)

Constructs a new instance for the given element type.

Method Summary

Modifier and TypeMethod and Description
public BiConsumer<List<O>, O>
accumulator()

Implements java.util.stream.Collector.accumulator.

A function that folds a value into a mutable result container.

public Set<Collector.Characteristics>
characteristics()

Implements java.util.stream.Collector.characteristics.

Returns a Set of Collector.Characteristics indicating the characteristics of this Collector.

public BinaryOperator<List<O>>
combiner()

Implements java.util.stream.Collector.combiner.

A function that accepts two partial results and merges them.

public Function<List<O>, O[]>
finisher()

Implements java.util.stream.Collector.finisher.

Perform the final transformation from the intermediate accumulation type A to the final result type R.

public Supplier<List<O>>
supplier()

Implements java.util.stream.Collector.supplier.

A function that creates and returns a new mutable result container.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

characteristicsback to summary
private static final Set<Collector.Characteristics> characteristics
elementTypeback to summary
private final Class<O> elementType

Constructor Detail

ArrayCollectorback to summary
public ArrayCollector(final Class<O> elementType)

Constructs a new instance for the given element type.

Parameters
elementType:Class<O>

The element type.

Method Detail

accumulatorback to summary
public BiConsumer<List<O>, O> accumulator()

Implements java.util.stream.Collector.accumulator.

Doc from java.util.stream.Collector.accumulator.

A function that folds a value into a mutable result container.

Annotations
@Override
characteristicsback to summary
public Set<Collector.Characteristics> characteristics()

Implements java.util.stream.Collector.characteristics.

Doc from java.util.stream.Collector.characteristics.

Returns a Set of Collector.Characteristics indicating the characteristics of this Collector. This set should be immutable.

Annotations
@Override
combinerback to summary
public BinaryOperator<List<O>> combiner()

Implements java.util.stream.Collector.combiner.

Doc from java.util.stream.Collector.combiner.

A function that accepts two partial results and merges them. The combiner function may fold state from one argument into the other and return that, or may return a new result container.

Annotations
@Override
finisherback to summary
public Function<List<O>, O[]> finisher()

Implements java.util.stream.Collector.finisher.

Doc from java.util.stream.Collector.finisher.

Perform the final transformation from the intermediate accumulation type A to the final result type R.

If the characteristic IDENTITY_FINISH is set, this function may be presumed to be an identity transform with an unchecked cast from A to R.

Annotations
@Override
supplierback to summary
public Supplier<List<O>> supplier()

Implements java.util.stream.Collector.supplier.

Doc from java.util.stream.Collector.supplier.

A function that creates and returns a new mutable result container.

Annotations
@Override
org.apache.commons.lang3 back to summary

public Class Streams.FailableStream<O>

extends Object
Class Inheritance
Annotations
@Deprecated
Type Parameters
<O>
The streams element type.

Deprecated

Use org.apache.commons.lang3.stream.Streams.FailableStream.

A reduced, and simplified version of a Stream with failable method signatures.

Field Summary

Modifier and TypeField and Description
private Stream<O>
private boolean

Constructor Summary

AccessConstructor and Description
public
FailableStream(final Stream<O>
The stream.
stream
)

Constructs a new instance with the given stream.

Method Summary

Modifier and TypeMethod and Description
public boolean

Returns:

true If either all elements of the stream match the provided predicate or the stream is empty, otherwise false.
allMatch
(final Functions.FailablePredicate<O, ?>
A non-interfering, stateless predicate to apply to elements of this stream.
predicate
)
References Deprecated Functions.FailablePredicate is deprecated or references (maybe indirectly) at least one deprecated element.

Returns whether all elements of this stream match the provided predicate.

public boolean

Returns:

true if any elements of the stream match the provided predicate, otherwise false.
anyMatch
(final Functions.FailablePredicate<O, ?>
A non-interfering, stateless predicate to apply to elements of this stream.
predicate
)
References Deprecated Functions.FailablePredicate is deprecated or references (maybe indirectly) at least one deprecated element.

Returns whether any elements of this stream match the provided predicate.

protected void
assertNotTerminated()

Throws IllegalStateException if this stream is already terminated.

public <
the intermediate accumulation type of the Collector.
A
,
the type of the result.
R
>
R

Returns:

the result of the reduction.
collect
(final Collector<? super O, A, R>
the Collector describing the reduction.
collector
)

Performs a mutable reduction operation on the elements of this stream using a Collector.

public <
Type of the accumulator.
A
,
type of the result.
R
>
R

Returns:

The result of the reduction.
collect
(final Supplier<R>
a function that creates a new result container. For a parallel execution, this function may be called multiple times and must return a fresh value each time.
supplier
,
final BiConsumer<R, ? super O>
An associative, non-interfering, stateless function for incorporating an additional element into a result.
accumulator
,
final BiConsumer<R, R>
An associative, non-interfering, stateless function for combining two values, which must be compatible with the accumulator function.
combiner
)

Performs a mutable reduction operation on the elements of this FailableStream.

public Streams.FailableStream<O>

Returns:

the new stream.
filter
(final Functions.FailablePredicate<O, ?>
a non-interfering, stateless predicate to apply to each element to determine if it should be included.
predicate
)
References Deprecated Functions.FailablePredicate and Streams.FailableStream are deprecated or reference (maybe indirectly) at least one deprecated element.

Returns a FailableStream consisting of the elements of this stream that match the given FailablePredicate.

public void
forEach(final Functions.FailableConsumer<O, ?>
a non-interfering action to perform on the elements.
action
)
References Deprecated Functions.FailableConsumer is deprecated or references (maybe indirectly) at least one deprecated element.

Performs an action for each element of this stream.

protected void
makeTerminated()

Marks this stream as terminated.

public <
The element type of the new stream.
R
>
Streams.FailableStream<R>

Returns:

the new stream.
map
(final Functions.FailableFunction<O, R, ?>
A non-interfering, stateless function to apply to each element.
mapper
)
References Deprecated Functions.FailableFunction and Streams.FailableStream are deprecated or reference (maybe indirectly) at least one deprecated element.

Returns a stream consisting of the results of applying the given function to the elements of this stream.

public O

Returns:

the result of the reduction.
reduce
(final O
the identity value for the accumulating function.
identity
,
final BinaryOperator<O>
an associative, non-interfering, stateless function for combining two values.
accumulator
)

Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.

public Stream<O>

Returns:

A stream, which will return the same elements, which this FailableStream would return.
stream
()

Converts the FailableStream into an equivalent stream.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

streamback to summary
private Stream<O> stream
terminatedback to summary
private boolean terminated

Constructor Detail

FailableStreamback to summary
public FailableStream(final Stream<O> stream)

Constructs a new instance with the given stream.

Parameters
stream:Stream<O>

The stream.

Method Detail

allMatchback to summary
public boolean allMatch(final Functions.FailablePredicate<O, ?> predicate)

References Deprecated

Functions.FailablePredicate is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated.

This is a short-circuiting terminal operation.

Note This method evaluates the universal quantification of the predicate over the elements of the stream (for all x P(x)). If the stream is empty, the quantification is said to be vacuously satisfied and is always true (regardless of P(x)).

Parameters
predicate:Functions.FailablePredicate<O, ?>

A non-interfering, stateless predicate to apply to elements of this stream.

Returns:boolean

true If either all elements of the stream match the provided predicate or the stream is empty, otherwise false.

anyMatchback to summary
public boolean anyMatch(final Functions.FailablePredicate<O, ?> predicate)

References Deprecated

Functions.FailablePredicate is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.

This is a short-circuiting terminal operation.

Note This method evaluates the existential quantification of the predicate over the elements of the stream (for some x P(x)).
Parameters
predicate:Functions.FailablePredicate<O, ?>

A non-interfering, stateless predicate to apply to elements of this stream.

Returns:boolean

true if any elements of the stream match the provided predicate, otherwise false.

assertNotTerminatedback to summary
protected void assertNotTerminated()

Throws IllegalStateException if this stream is already terminated.

Exceptions
IllegalStateException:
if this stream is already terminated.
collectback to summary
public <A, R> R collect(final Collector<? super O, A, R> collector)

Performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.

If the underlying stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed (see Collector for details on concurrent reduction.)

This is an intermediate operation.

When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.

Note The following will accumulate strings into an ArrayList:

List<String> asList = stringStream.collect(Collectors.toList());

The following will classify Person objects by city:

Map<String, List<Person>> peopleByCity
        = personStream.collect(Collectors.groupingBy(Person::getCity));

The following will classify Person objects by state and city, cascading two Collectors together:

Map<String, Map<String, List<Person>>> peopleByStateAndCity
        = personStream.collect(Collectors.groupingBy(Person::getState,
                                                     Collectors.groupingBy(Person::getCity)));
Parameters
<A>
the intermediate accumulation type of the Collector.
<R>
the type of the result.
collector:Collector<? super O, A, R>

the Collector describing the reduction.

Returns:R

the result of the reduction.

See Also
collect(Supplier, BiConsumer, BiConsumer), Collectors
collectback to summary
public <A, R> R collect(final Supplier<R> supplier, final BiConsumer<R, ? super O> accumulator, final BiConsumer<R, R> combiner)

Performs a mutable reduction operation on the elements of this FailableStream. A mutable reduction is one in which the reduced value is a mutable result container, such as an ArrayList, and elements are incorporated by updating the state of the result rather than by replacing the result. This produces a result equivalent to:

R result = supplier.get();
    for (T element : this stream)
        accumulator.accept(result, element);
    return result;

Like reduce(Object, BinaryOperator), collect operations can be parallelized without requiring additional synchronization.

This is an intermediate operation.

Note There are many existing classes in the JDK whose signatures are well-suited for use with method references as arguments to collect(). For example, the following will accumulate strings into an ArrayList:

List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add,
                                               ArrayList::addAll);

The following will take a stream of strings and concatenates them into a single string:

String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
                                         StringBuilder::append)
                                .toString();
Parameters
<A>
Type of the accumulator.
<R>
type of the result.
supplier:Supplier<R>

a function that creates a new result container. For a parallel execution, this function may be called multiple times and must return a fresh value each time.

accumulator:BiConsumer<R, ? super O>

An associative, non-interfering, stateless function for incorporating an additional element into a result.

combiner:BiConsumer<R, R>

An associative, non-interfering, stateless function for combining two values, which must be compatible with the accumulator function.

Returns:R

The result of the reduction.

filterback to summary
public Streams.FailableStream<O> filter(final Functions.FailablePredicate<O, ?> predicate)

References Deprecated

Functions.FailablePredicate and Streams.FailableStream are deprecated or reference (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Returns a FailableStream consisting of the elements of this stream that match the given FailablePredicate.

This is an intermediate operation.

Parameters
predicate:Functions.FailablePredicate<O, ?>

a non-interfering, stateless predicate to apply to each element to determine if it should be included.

Returns:Streams.FailableStream<O>

the new stream.

forEachback to summary
public void forEach(final Functions.FailableConsumer<O, ?> action)

References Deprecated

Functions.FailableConsumer is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Performs an action for each element of this stream.

This is an intermediate operation.

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.

Parameters
action:Functions.FailableConsumer<O, ?>

a non-interfering action to perform on the elements.

makeTerminatedback to summary
protected void makeTerminated()

Marks this stream as terminated.

Exceptions
IllegalStateException:
if this stream is already terminated.
mapback to summary
public <R> Streams.FailableStream<R> map(final Functions.FailableFunction<O, R, ?> mapper)

References Deprecated

Functions.FailableFunction and Streams.FailableStream are deprecated or reference (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Returns a stream consisting of the results of applying the given function to the elements of this stream.

This is an intermediate operation.

Parameters
<R>
The element type of the new stream.
mapper:Functions.FailableFunction<O, R, ?>

A non-interfering, stateless function to apply to each element.

Returns:Streams.FailableStream<R>

the new stream.

reduceback to summary
public O reduce(final O identity, final BinaryOperator<O> accumulator)

Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. This is equivalent to:

T result = identity;
    for (T element : this stream)
        result = accumulator.apply(result, element)
    return result;
but is not constrained to execute sequentially.

The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t. The accumulator function must be an associative function.

This is an intermediate operation.

Note Sum, min, max, average, and string concatenation are all special cases of reduction. Summing a stream of numbers can be expressed as:
Integer sum = integers.reduce(0, (a, b) -> a+b);
or:
Integer sum = integers.reduce(0, Integer::sum);

While this may seem a more roundabout way to perform an aggregation compared to simply mutating a running total in a loop, reduction operations parallelize more gracefully, without needing additional synchronization and with greatly reduced risk of data races.

Parameters
identity:O

the identity value for the accumulating function.

accumulator:BinaryOperator<O>

an associative, non-interfering, stateless function for combining two values.

Returns:O

the result of the reduction.

streamback to summary
public Stream<O> stream()

Converts the FailableStream into an equivalent stream.

Returns:Stream<O>

A stream, which will return the same elements, which this FailableStream would return.