0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

List内の指定した要素のインデックスを取得する【Kotlin】

Posted at

はじめに

Listから要素を検索しインデックスを取得します。
Kotlinでは、上記の処理をする関数がいくつかあるため紹介します。

紹介する関数は公式を参照しています。
バージョンは、Kotlin1.5です。

indexOf,lastIndexOf

一致する一番最初の要素のインデックスを取得します。
該当するものがない場合は -1 を返します。
lastIndexOfは最後の方から探索します。

val list = mutableListOf('a', 'b', 'c', 'd', 'e', 'd')
println(list.indexOf('d')) // 3
println(list.lastIndexOf('d')) // 5
list.remove('d')
println(list.indexOf('d')) // -1
println(list.lastIndexOf('d')) // -1


binarySearch,binarySearchBy

バイナリサーチで指定した要素のインデックスを取得します。
指定した要素が存在しない場合は 負の値 を返します。
ソートがされている前提なので、ソートがされていないと正しく動作しません。
引数でオプション(始点・終点・比較方法など)を設定できます。
binarySearchByは要素を変換したうえで探索することができます。

val list = mutableListOf('a', 'b', 'c', 'd', 'e')
println(list.binarySearch('d')) // 3
println(numberList.binarySearch(element = 2, fromIndex = 0, toIndex = 3))
println(numberList.binarySearch(element = 2, comparator = Comparator { a, b -> a - b }))
println(numberList.binarySearchBy(2, selector = { it }))

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?