There are a few operations that processes a stream and output stream as source for terminal operations. Above, we can see some of these methods, yours descriptions and examples. Just short, just directly.
Filtering and Mapping
discinct()
- Returns a stream with no duplicate elements.
filter(Predicate p)
- Returns a stream with only those elements that return true for the Predicate.
map(Function f)
- Returns a stream where the given Function is applied to each element on the input stream.
mapToInt(), mapToDouble(), mapToLong()
- Like map(), but producing streams of primitives rather than objects
Maps and FlatMaps
Map:
- Take a single value as input and generates a single value of output stream. 1-to-1 mapping.
FlatMap:
- Streams of stream. Take the input stream, generates a stream for each element and join the result.
Ex.:
List<String> output = reader.lines().flatMap(line -> Stream.of(line.split(REGEXP))).filger(word -> word.length() > 0).collect(Collectors.toList());
Restricting the size of a stream
skip(long n)
limit(long n)
Ex.: String output = bufferedReader.lines().skip(2).limit(2).collect(Collectors.joining());
Sorting and unsorting
sorted(Comparator c)
- sorted(): based on natural order.
unordered()
- can improve efficiency of operations like distinct() and groupingby()
Observing Stream Elements
Peek
- Not modify the elements of the stream. Each of element is passed by the accpet() metodh of the Consumer.