valstr="kotlin very good"// 如果未查找到满足条件的元素,会抛出NoSuchElementException异常str.last{ it =='o'}// 其实从源码中我们发现其是对原字符串反转之后再进行遍历查找满足条件的元素。复制代码 lastOrNull()同firstOrNUll()一样。lastOrNull{}同firstOrNUll{}一样。 1.3、查找元素 其实查找元素提供...
print("The index of last occurrence of element is : $index") } Output The index of last occurrence of element is : 3 Example 2: List.lastIndexOf() – Element not in the List In this example, we will try to find the output of List.lastIndexOf() function, when the element is not...
publicinlinefun<T>Iterable<T>.filter(predicate:(T)->Boolean):List<T>{returnfilterTo(ArrayList<T>(),predicate)}publicinlinefun<T,C:MutableCollection<inT>>Iterable<T>.filterTo(destination:C,predicate:(T)->Boolean):C{for(elementinthis)if(predicate(element))destination.add(element)returndestination...
findXxx():一系列用于查找元素的方法 first|last(predicate:(T)->Boolean):获取数组中第一个或最后一个符合predicate条件的元素 indexOf|lastIndexOf(element T):获取从前搜索或从后搜索时元素element在数组中的索引 indexOfFirst|indexOfLast(predicate(T):->Boolean)返回第一个或最后一个符合predicate条件的元素的...
val str = "kotlin very good"// 如果未查找到满足条件的元素,会抛出NoSuchElementException异常str.first{ it == 'o' } 还有一个firstOrNull()函数,它和first()函数的区别在于如果字符串为空串时,first()函数会抛出异常,而firstOrNull()函数会返回null。当然还有firstOrNull{}函数,它和first{}函数的区别在...
NoSuchElementException: Collection contains no element matching the predicate.错误 如果要避免异常的产生,就需要使用他们的安全写法firstOrNull()和lastOrNull() 写法是一样的,如果没有查询到,就会返回null对象。 代码语言:javascript 复制 funmain(string:Array<String>){val test=listOf("one","two","three"...
for ((index,element) in strList.withIndex()) { println("$index $element") } } 1. 2. 3. 4. 5. 6. sort 排序相关的方法 var listOf = mutableListOf<String>("123", "4564", "78944") // 这种写法和循环一样,每一个元素都是it且是正序排列的 ...
Each element of a list has an index. Kotlin list indexes start from zero. The last element haslen-1index. ListIndex.kt package com.zetcode fun main() { val words = listOf("pen", "cup", "dog", "person", "cement", "coal", "spectacles", "cup", "bread") ...
add(element:E) 添加元素到set集合中 addAll(elements:Collection<E>) 批量添加一个集合到集合中 //创建一个可变集合val mutableSetOf=mutableSetOf("疯狂C")//添加一个元素mutableSetOf.add("疯狂java")//批量添加一个集合到set集合中mutableSetOf.addAll(setOf("Java","Kotlin"))println(mutableSetOf) ...
(origins)// 删除符合条件的第一条element: [two, three]origins[0] ="newOne"println(origins)// 更新第一条数据:[newOne, three]origins.shuffle()println(origins)// 随机数据:[three, newOne]origins.removeAll{ it.length==3}println(origins)//删除全部符合条件的元素 [three, newOne]println(origins...