Thursday, May 21, 2020

Kotlin vs java continued

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.

Lists order elements by position. Two lists cannot be considered similar if their elements are not in the same order.
Order can be ‘natural’ if the elements in the collection implement the Comparable interface. The Comparable interface has a method called compareTo which has a major version and a minor version. This is the default order when none other is specified.
Custom orders helps sort instances in any arbitrary way. Even if the objects cannot be compared, it is possible to override the compare method of the Comparator interface in this case. For example,
companion object: Comparator<ReaderConfiguration> {
         override fun compare(a: ReaderConfiguration, b: ReaderConfiguration): Int {
                        if (a.numReaders == b.numReaders &&
                            a.numRetries == b.numRetries &&
                            a.retryMillis == b.retryMillis && 
                            a.segment == b.segment &&
                            a.position == b.position ) return 0
                        return -1
        }
    }
Then there is reverse order by running the extension function reversed() on the collection. This creates a new collection. If we want the same collection reversed, the asReversed() method comes helpful.

1 comment: