kotlin Exception「Exception in thread “main” java.util.NoSuchElementException: Collection contains no element matching the predicate.」の解決方法
kotlinで、Exception「Exception in thread “main” java.util.NoSuchElementException: Collection contains no element matching the predicate.」の解決方法を記述してます。
環境
- OS windows11 home
- java 17.0.2
- kotlin 1.6.10-release-923
エラー全文
以下のコードで発生。
fun main() {
val list = listOf(10, 20, 30)
println(list.first { it > 30 })
}
Exception
※ファイル名は「hello.kt」
Exception in thread "main" java.util.NoSuchElementException:
Collection contains no element matching the predicate.
at HelloKt.main(hello.kt:10)
at HelloKt.main(hello.kt)
原因
「first」で条件に指定した値を満たす要素がないため
対処法
「firstOrNull」を使用して、条件を満たさない場合は「null」を返す。
fun main() {
val list = listOf(10, 20, 30)
println(list.firstOrNull { it > 30 }) // null
}
-
前の記事
javascript エラー「Uncaught TypeError: xxx.pop is not a function」の解決方法 2022.10.12
-
次の記事
javascript setの結合処理で「スプレッド構文」と「addを使用した関数」のパフォーマンスを計測する 2022.10.12
コメントを書く