Source #
Collection #
A stream can be created out of a Java Collection with the instance method stream
.
Example.
List<Unit> units = getUnits(); units.stream();
If the collection has a predictable order of iteration (e.g. if the collection is a List
), then the elements will appear in this order in the stream.
To create a stream out of the entries of a map, we can use the instance method Map.entrySet that we have seen earlier. It returns a Set
(which is a collection).
Example.
Map<String, Integer> map = getMap(); map.entrySet().stream();
Array #
A stream can be created out of a Java array with the static method Arrays.stream
.
Example.
Unit[] units = getUnits(); Arrays.stream(units);
Generate a stream with indices #
An IntStream
is a stream of int
(see the dedicated section on streams with primitive numeric types).
An IntStream
can for instance be created with the static method IntStream.range
, as follows:
Example.
// Contains [0, 2] List<Unit> evenIntegers = IntStream.range(0, 4) // produce the stream (0, 1, 2, 3) .filter(i -> i % 2 == 0) // retain even numbers .toList();
This can be used to iterate over a list or array while keeping track of the elements’ positions.
Example.
Unit[] units = getUnits(); List<Unit> evenUnits = IntStream.range(0, units.length) .filter(i -> i % 2 == 0) .mapToObj(i -> units[i]) .toList();
However, for this usage, external libraries offer more natural options. For instance, the StreamEx library can create a map from index to entry in an array, and generate a stream out of the entries of this map (analogous to the set of entries produced by Map.entrySet).
Unit[] units = getUnits();
List<Unit> evenUnits = EntryStream.of(units)
.filterKeyValue((index, unit) -> index % 2 == 0)
.values()
.toList();
}
To use StreamEx in a Maven project, declare this dependency:
<dependencies>
...
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>0.8.2</version>
<scope>runtime</scope>
</dependency>
...
</dependencies>
or in a Gradle project:
implementation group: 'one.util', name: 'streamex', version: '0.8.2'