Categories
Studio

Kotlin for Interviews — Part 2: Collection Functions | by Sherry Yuan

Sherry Yuan
Photo courtesy Susan Inn on Release the splash

This is Part 2 of Kotlin for Interviews. This series describes Kotlin’s functions and code snippets that came up frequently while preparing for an Android interview. We have also created a cheat sheet that covers all five parts of this series. Here..

Part 1: You can find common data types Here, Part 3: Numbers and Mathematics Here, Part 4: Iteration and Part Here And Part 5: Frequently used code snippets Here..

The contents of this part are as follows:

  1. Getter
  2. Search and find
  3. Sorting
  4. Boule summary
  5. Statistical summary

The Kotlin Standard Library provides many functions for performing operations on collections.I’ll only cover the ones I use most often in interview issues, but here’s Great article It gives an overview of all of them.

  • get(key: V) Is a basic getter and returns the value of the index or key you passed. You can also use the following in Kotlin: someCollection[key] As a getter.
  • getOrDefault(key: K, defaultValue: V) Returns the value to which the specified key is mapped. Returns defaultValue if this map does not contain a key mapping. This is useful for working with maps.
  • getOrNull(index: Int) Returns the element at the specified index null If the index is out of range. This is useful when working with arrays and lists.
  • first(predicate: (T) -> Boolean): T Returns the first element that matches the specified predicate. If no element matches the predicate, an exception will be thrown.
  • firstOrNull(predicate: (T) -> Boolean): T? And find(predicate: (T) -> Boolean): T? Both return the first element that matches the specified predicate, or null If no such element is found. They can be used interchangeably.
// Example of first()
val numbers = listOf("one", "two", "three", "four", "five", "six")
numbers.first { it.length > 3 } // returns “three”
numbers.first { it.length > 8 } // throws NoSuchElementException
numbers.firstOrNull { it.length > 8 } // returns null
numbers.find { it.length > 8 } // returns null
  • last(predicate: (T) -> Boolean): T Returns the last element that matches the specified predicate. If no element matches the predicate, an exception will be thrown.
  • lastOrNull(predicate: (T) -> Boolean): T And findLast(predicate: (T) -> Boolean): T Both return the last element that matches the specified predicate, or null If no such element is found. They can be used interchangeably.
  • indexOf(element: T): Int Returns the first index of the element, or -1 If the array contains no elements.
  • lastIndexOf(element: T): Int Returns the last index of the element, or -1 If the array contains no elements.
  • indexOfFirst(predicate: (T) -> Boolean): Int Returns the index of the first element that matches the specified predicate, or -1 If the array contains no elements.
  • indexOfFirst(predicate: (T) -> Boolean): Int Returns the index of the last element that matches the specified predicate, or -1 If the array contains no elements.
  • binarySearch(element: T?): Int Finds the element in the sorted collection and returns its index.
  • binarySearchBy(key: K?, selector: (T) -> K?): Int Finds the element whose key returned by the specified selector function is equal to the specified key value and returns its index.
// Example of binarySearchBy()
data class Box(val number: Int)
val numbers = listOf(Box(1), Box(3), Box(7), Box(10), Box(12))
// returns 3 because the element at index 3 has it.number == 10.
boxes.binarySearchBy(10) { it.number }
  • sort() Sort in ascending order, using the natural order of the elements. The sort method sorts the specified collection on the fly and returns nothing.
  • sorted(): List<T> Sorts in ascending order using the natural order of the elements and returns the result.
  • sortBy(selector: (T) -> R?) Sorts the elements in-place in ascending order according to the sort order of the values ​​returned by the specified selector function. Returns nothing.
  • sortedBy(selector: (T) -> R?): List<T> Sorts in ascending order using the sort order of the values ​​returned by the specified selector function and returns the result.
  • sortWith(comparator: Comparator<in T>) Sorts the collection in-place in ascending order using the order specified by the specified comparator. Returns nothing. To Kotlin compareBy()Functions to help you create Comparator Easy object.
  • sortedWith(comparator: Comparator<in T>): List<T> Sorts the collection in ascending order using the order specified by the specified comparator and returns the result.
  • sortDescending(), sortedDescending(), sortByDescending(), And sortedByDescending() It has the same effect as the above function, but in descending order.
// Need to use a mutableList since sort() mutates the list
val sortNumbers = mutableListOf(1, 2, 7, 6, 5, 6)
sortNumbers.sort()
// sortNumbers becomes [1, 2, 5, 6, 7]
val sortValues = mutableListOf(1 to "a", 5 to "c", 2 to "c", 7 to "b", 6 to "d")
sortValues.sortBy { it.second }

// sortValues becomes [(1, a), (7, b), (5, c), (2, c), (6, d)]
// sort by letter, and then by number
sortValues.sortWith(compareBy({it.second}, {it.first}))
// sortValues becomes [(1, a), (7, b), (2, c), (5, c), (6, d)]

Too many different sort functions can be confusing, so I created the following table to summarize them.

All of these functions evaluate the predicate through all the relevant elements and return a Boolean result.

  • all() Returns true if all elements match the specified predicate.
  • any() Returns true if there is an element that matches the specified predicate.
  • none() Returns true if no element matches the specified predicate.
  • contains() Returns true if the specified element is found in the collection.
  • isEmpty() Returns true if the collection is empty.If your collection is nullable, you can use: isNullOrEmpty().. For strings, you can use: isNullOrBlank().. These are often useful as a condition for ending a while loop or as a check for the basic case of a recursive function.

These functions evaluate all the elements and then return a number that represents the statistical result.

  • average() Returns the average of the elements in the collection.
  • count() Returns the number of elements in the collection.
  • maxOrNull() Returns the largest element. Returns null if there are no elements.
  • We also have max(), maxBy(),and maxWith() Returns the maximum value of the collection using natural ordering, selector functions, and comparators, respectively. They follow the same naming pattern as the sort function.
  • min(), minBy(),and minWith() It uses natural ordering, selector functions, and comparators, respectively, to return the minimum value in the collection.
  • sum() Returns the sum of all the elements in the collection.
  • sumBy() Returns the sum of all the values ​​generated by a particular selector function applied to each element in the collection.

This is Link to cheat sheet Cover all five parts again.

This is the end of Part 2.To Part 3Look up numbers and math in Kotlin.

Source

Leave a Reply

Your email address will not be published. Required fields are marked *