Methods in streams in Java
Difference between Collection and Stream
Collections allow you to work with elements separately, while streams do not allow you to do this, but instead provide the ability to perform functions on the data as a whole.
It is also worth noting the importance of the very concept of entities: Collection is, first of all, the embodiment of the Data Structure. For example, Set does not just store elements in itself, it implements the idea of a set with unique elements, while Stream is, first of all, an abstraction necessary for the implementation of a pipeline of calculations, in fact, therefore, the result of the pipeline operation is certain Data Structures or the results of checks/searches etc.
collect() method in streams
The collect() method is the terminal operation that is used to represent the result as a collection or some other data structure.
collect() takes as input Collector<source_type, accumulator_type, result_type>, which contains four stages: supplier - initializing the accumulator, accumulator - processing each element, combiner - concatenating two accumulators in parallel, [finisher] - an optional method of the last accumulator processing. In Java 8, the Collectors class implements several common collectors:
- toList(), toCollection(), toSet() - represent the stream as a list, collection or set;
- toConcurrentMap(), toMap() - allow converting the stream to Map;
- averagingInt(), averagingDouble(), averagingLong() - return the average value;
- summingInt(), summingDouble(), summingLong() - returns the amount;
- summarizingInt(), summarizingDouble(), summarizingLong() - return SummaryStatistics with different aggregate values;
- partitioningBy() - splits the collection into two parts according to the condition and returns them as Map<Boolean, List>;
- groupingBy() - splits the collection into several parts and returns Map<N, List<T>>;
- mapping() - additional transformations of values for complex Collectors.
It is also possible to create your own collector through Collector.of():
Collector<String, List<String>, List<String>> toList = Collector.of(
ArrayList::new,
List::add,
(l1, l2) -> { l1.addAll(l2); return l1; }
);
forEach() and forEachOrdered() methods in streams
- forEach() applies a function to each stream object, the order in parallel execution is not guaranteed;
- forEachOrdered() applies a function to each stream object while maintaining the order of the elements.
map() and mapToInt(), mapToDouble(), mapToLong() methods in streams
The map() method is an intermediate operation that transforms each element of the stream in a given way.
mapToInt(), mapToDouble(), mapToLong() are analogs of map() that return the corresponding numeric stream (that is, a stream from numeric primitives):
Stream
.of("12", "22", "4", "444", "123")
.mapToInt(Integer::parseInt)
.toArray(); //[12, 22, 4, 444, 123]
Purpose of the filter() method in streams
The filter() method is an intermediate operation that accepts a predicate that filters all elements, returning only those that match the condition.
limit() method in streams
The limit() method is an intermediate operation that allows you to limit the selection to a certain number of first elements.
sorted() method in streams
The sorted() method is an intermediate operation that allows you to sort values either in natural order or by specifying a Comparator.
The order of the elements in the original collection remains intact - sorted() only creates a sorted view of it.
Methods flatMap(), flatMapToInt(), flatMapToDouble(), flatMapToLong() in streams
The flatMap() method is similar to map, but it can create multiple elements from one element. This way every object will be converted to zero, one or more other objects supported by the thread. The most obvious way to use this operation is to transform the elements of a container using functions that return containers.
Stream
.of("H e l l o", "w o r l d !")
.flatMap((p) -> Arrays.stream(p.split(" ")))
.toArray(String[]::new);
//["H", "e", "l", "l", "o", "w", "o", "r", "l", "d", "!"]
flatMapToInt(), flatMapToDouble(), flatMapToLong() are analogs of flatMap() that return the corresponding numeric stream.
Read also:
Comments
Post a Comment