- List
- Parameters
- Properties
- size
- Functions
- contains
- containsAll
- get
- indexOf
- isEmpty
- iterator
- lastIndexOf
- listIterator
- subList
- Extension Properties
- indices
- lastIndex
- Extension Functions
- all
- any
- asIterable
- asReversed
- asSequence
- associate
- associateBy
- associateByTo
- associateTo
- associateWith
- associateWithTo
- binarySearch
- List-specific operations
- Retrieve elements by index
- Retrieve list parts
- Find element positions
- Linear search
- Binary search in sorted lists
- Comparator binary search
- Comparison binary search
- List write operations
- Add
- Update
- Remove
- Sort
- Найти индекс элемента в списке Kotlin
- 1. Использование indexOf() функция
- 2. Использование withIndex() функция
- 3. Использование find() функция
- 4. Использование цикла
List
A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.
Parameters
E — the type of elements contained in the list. The list is covariant in its element type.
Properties
size
Returns the size of the collection.
Functions
contains
Checks if the specified element is contained in this collection.
containsAll
Checks if all elements in the specified collection are contained in this collection.
get
Returns the element at the specified index in the list.
indexOf
Returns the index of the first occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.
isEmpty
Returns true if the collection is empty (contains no elements), false otherwise.
iterator
Returns an iterator over the elements of this object.
lastIndexOf
Returns the index of the last occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.
listIterator
Returns a list iterator over the elements in this list (in proper sequence).
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified index.
subList
Returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
Extension Properties
indices
Returns an IntRange of the valid indices for this collection.
lastIndex
Returns the index of the last item in the list or -1 if the list is empty.
Extension Functions
all
Returns true if all elements match the given predicate.
any
Returns true if collection has at least one element.
Returns true if at least one element matches the given predicate.
asIterable
Returns this collection as an Iterable.
asReversed
Returns a reversed read-only view of the original List. All changes made in the original list will be reflected in the reversed one.
asSequence
Creates a Sequence instance that wraps the original collection returning its elements when being iterated.
associate
Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.
associateBy
Returns a Map containing the elements from the given collection indexed by the key returned from keySelector function applied to each element.
Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.
associateByTo
Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given collection and value is the element itself.
Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function applied to elements of the given collection.
fun < T , K , V , M : MutableMap < in K , in V >> Iterable < T >. associateByTo (
destination : M ,
keySelector : ( T ) -> K ,
valueTransform : ( T ) -> V
) : M
associateTo
Populates and returns the destination mutable map with key-value pairs provided by transform function applied to each element of the given collection.
associateWith
Returns a Map where keys are elements from the given collection and values are produced by the valueSelector function applied to each element.
associateWithTo
Populates and returns the destination mutable map with key-value pairs for each element of the given collection, where key is the element itself and value is provided by the valueSelector function applied to that key.
binarySearch
Searches this list or its range for the provided element using the binary search algorithm. The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements, otherwise the result is undefined.
fun < T : Comparable < T >> List < T ? >. binarySearch (
element : T ? ,
fromIndex : Int = 0 ,
toIndex : Int = size
) : Int
Searches this list or its range for the provided element using the binary search algorithm. The list is expected to be sorted into ascending order according to the specified comparator, otherwise the result is undefined.
fun < T > List < T >. binarySearch (
element : T ,
comparator : Comparator < in T >,
fromIndex : Int = 0 ,
toIndex : Int = size
) : Int
Searches this list or its range for an element for which the given comparison function returns zero using the binary search algorithm.
fun < T > List < T >. binarySearch (
fromIndex : Int = 0 ,
toIndex : Int = size ,
comparison : ( T ) -> Int
) : Int
List-specific operations
List is the most popular type of built-in collection in Kotlin. Index access to the elements of lists provides a powerful set of operations for lists.
Retrieve elements by index
Lists support all common operations for element retrieval: elementAt() , first() , last() , and others listed in Retrieve single elements. What is specific for lists is index access to the elements, so the simplest way to read an element is retrieving it by index. That is done with the get() function with the index passed in the argument or the shorthand [index] syntax.
If the list size is less than the specified index, an exception is thrown. There are two other functions that help you avoid such exceptions:
- getOrElse() lets you provide the function for calculating the default value to return if the index isn’t present in the collection.
- getOrNull() returns null as the default value.
Retrieve list parts
In addition to common operations for Retrieving Collection Parts, lists provide the subList() function that returns a view of the specified elements range as a list. Thus, if an element of the original collection changes, it also changes in the previously created sublists and vice versa.
Find element positions
Linear search
In any lists, you can find the position of an element using the functions indexOf() and lastIndexOf() . They return the first and the last position of an element equal to the given argument in the list. If there are no such elements, both functions return -1 .
There is also a pair of functions that take a predicate and search for elements matching it:
- indexOfFirst() returns the index of the first element matching the predicate or -1 if there are no such elements.
- indexOfLast() returns the index of the last element matching the predicate or -1 if there are no such elements.
Binary search in sorted lists
There is one more way to search elements in lists – binary search. It works significantly faster than other built-in search functions but requires the list to be sorted in ascending order according to a certain ordering: natural or another one provided in the function parameter. Otherwise, the result is undefined.
To search an element in a sorted list, call the binarySearch() function passing the value as an argument. If such an element exists, the function returns its index; otherwise, it returns (-insertionPoint — 1) where insertionPoint is the index where this element should be inserted so that the list remains sorted. If there is more than one element with the given value, the search can return any of their indices.
You can also specify an index range to search in: in this case, the function searches only between two provided indices.
Comparator binary search
When list elements aren’t Comparable , you should provide a Comparator to use in the binary search. The list must be sorted in ascending order according to this Comparator . Let’s have a look at an example:
Here’s a list of Product instances that aren’t Comparable and a Comparator that defines the order: product p1 precedes product p2 if p1 ‘s price is less than p2 ‘s price. So, having a list sorted ascending according to this order, we use binarySearch() to find the index of the specified Product .
Custom comparators are also handy when a list uses an order different from natural one, for example, a case-insensitive order for String elements.
Comparison binary search
Binary search with comparison function lets you find elements without providing explicit search values. Instead, it takes a comparison function mapping elements to Int values and searches for the element where the function returns zero. The list must be sorted in the ascending order according to the provided function; in other words, the return values of comparison must grow from one list element to the next one.
Both comparator and comparison binary search can be performed for list ranges as well.
List write operations
In addition to the collection modification operations described in Collection write operations, mutable lists support specific write operations. Such operations use the index to access elements to broaden the list modification capabilities.
Add
To add elements to a specific position in a list, use add() and addAll() providing the position for element insertion as an additional argument. All elements that come after the position shift to the right.
Update
Lists also offer a function to replace an element at a given position — set() and its operator form [] . set() doesn’t change the indexes of other elements.
fill() simply replaces all the collection elements with the specified value.
Remove
To remove an element at a specific position from a list, use the removeAt() function providing the position as an argument. All indices of elements that come after the element being removed will decrease by one.
Sort
In Collection Ordering, we describe operations that retrieve collection elements in specific orders. For mutable lists, the standard library offers similar extension functions that perform the same ordering operations in place. When you apply such an operation to a list instance, it changes the order of elements in that exact instance.
The in-place sorting functions have similar names to the functions that apply to read-only lists, but without the ed/d suffix:
- sort* instead of sorted* in the names of all sorting functions: sort() , sortDescending() , sortBy() , and so on.
- shuffle() instead of shuffled() .
- reverse() instead of reversed() .
asReversed() called on a mutable list returns another mutable list which is a reversed view of the original list. Changes in that view are reflected in the original list. The following example shows sorting functions for mutable lists:
fun main() < //sampleStart val numbers = mutableListOf("one", "two", "three", "four") numbers.sort() println("Sort into ascending: $numbers") numbers.sortDescending() println("Sort into descending: $numbers") numbers.sortBy < it.length >println(«Sort into ascending by length: $numbers») numbers.sortByDescending < it.last() >println(«Sort into descending by the last letter: $numbers») numbers.sortWith(compareBy
Найти индекс элемента в списке Kotlin
В этой статье рассматриваются различные способы поиска индекса элемента в списке Kotlin.
1. Использование indexOf() функция
Рекомендуемое решение для получения индекса элемента в списке — это indexOf() библиотечная функция. Он возвращает индекс первого вхождения предоставленного элемента в список или -1 если элемента нет.
2. Использование withIndex() функция
Идея здесь состоит в том, чтобы получить итерацию, содержащую индекс каждого элемента списка и сам элемент, используя withIndex() функция. Затем верните индекс первой пары, которая соответствует заданному значению. Это будет переведено в следующий код:
3. Использование find() функция
Другой жизнеспособной альтернативой является фильтрация индексов, содержащих данный элемент, с помощью find() функция, которая возвращает первый элемент, соответствующий заданному предикату, или null если такого элемента не существует. Это приведет к простому коду ниже:
4. Использование цикла
Ниже приведена эквивалентная версия с использованием цикла for, который возвращает индекс первого вхождения или -1 если соответствующий элемент не найден.
Это все, что касается поиска индекса элемента в списке Kotlin.
Средний рейтинг 5 /5. Подсчет голосов: 12
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно