Skip to main content

Stream API

lib/stream/Stream.mt provides a Java-style chainable stream over any Iterable<T>.

Building a Stream

Every collection has a stream() method:

import * from "lib/primitives/Int.mt";
import * from "lib/collections/ArrayList.mt";

ArrayList<Int> numbers = new ArrayList<Int>();
numbers.add(new Int(1));
numbers.add(new Int(2));
numbers.add(new Int(3));

Stream<Int> s = numbers.stream();

Chaining Operations

Int sum = numbers.stream()
.filter(x -> x > 2)
.map(x -> x * 10)
.reduceWithIdentity(0, (a, b) -> a + b);

print(sum);

Operations

OperationKindDescription
filter(Predicate<T>)intermediateKeep elements matching the predicate.
map(Function<T, R>)intermediateTransform each element.
flatMap(Function<T, Stream<R>>)intermediateFlatten nested streams.
distinct()intermediateRemove duplicates.
sorted(Comparator<T>)intermediateSort with a comparator.
limit(int)intermediateTake the first N.
skip(int)intermediateDrop the first N.
reduce(BinaryOperator<T>)terminalFold without an identity.
reduceWithIdentity(T, BinaryOperator<T>)terminalFold with an identity.
forEach(Consumer<T>)terminalSide-effect each element.
toList()terminalCollect to an ArrayList<T>.
count()terminalNumber of elements.

Example: Word Count

ArrayList<String> words = ...;
HashMap<String, int> counts = new HashMap<String, int>();
words.stream().forEach(w -> {
if (counts.containsKey(w)) {
counts.put(w, counts.get(w) + 1);
} else {
counts.put(w, 1);
}
});

See Also