Tuesday, May 19, 2020

Kotlin vs Java continued

Collections are provided in the Kotlin standard library via extension functions.  For example, groupBy takes a lambda function and returns a Map where each key is the lambda result and the corresponding value is the List of elements which represent the groups 

The groupBy can also be called with a second parameter 'valueTransform' where the keys from the first parameter 'keySelector' is mapped to the result of the transformation rather than the original elements.  

groupBy is different from groupingBy which returns an instance of 'Grouping' type. Here the operations are all applied in a lazy manner. Even the groups are formed just before the operation execution and supports the following operations: 

eachCount() which counts the elements in each group 

fold() and reduce() which operates on each group and returns results 

aggregate() which supports custom operations when fold and reduce are not enough     

Collections can be retrieved with 

 - slice 

 - take and drop 

 - chunked and 

 - windowed

slice() returns a list of collection when a set of indices are passed in. The positions of the elements to be retrieved can also be passed in via range descriptors. This is equivalent to subList

Take and drop  are functions that return the elements themselves.

take() and takeLast() work on the two ends of the list. If there are more number of elements specified than the current number, then they return the entire collection.

drop() returns elements not matching the given predicate.

chunked breaks the collection into parts of a given size, all parts are of equal size unless the remaining are smaller than the chunk size. chunks are short living lists that should be consumed right in that lambda.

Windowed retrieves all possible ranges of the collection elements of a given size starting from each collection element.


 

 

 
 

No comments:

Post a Comment