关于集合操作中异常:Collection contains no element matching the predicate.

Collection contains no element matching the predicate.译为:集合不包含与谓词匹配的元素。

出错的代码是这样的:

userRepo.findByRoleTag(roleTag).first { it.userName == "Amethyst" }

一般集合中去匹配按照一定条件进行筛选 比如last first 这些,都需要判空,如果不对null进行处理就会报这样的异常。解决方案就是:

userRepo.findByRoleTag(roleTag).firstOrNull { it.userName == "Amethyst" }

这里传送一个讲解kotlin集合的网址

样例记录:

 println(list.contains(2))

 println(list.elementAt(1))
 //println(list.elementAt(11))  //java.lang.ArrayIndexOutOfBoundsException: 11
 println(list.elementAtOrElse(10, { 2 * it }))
 println(list.elementAtOrNull(10))

  println(list.first { it % 2 == 0 })
  //println(list.first { it % 2 == 10 })  //java.util.NoSuchElementException: Collection contains no element matching the predicate
 println(list.firstOrNull() { it % 2 == 10 })

 println(list.indexOf(4))
 println(list.indexOfFirst { it % 2 == 0 })
 println(list.indexOfLast { it % 2 == 0 })

 println(list.last { it % 2 == 0 })
 //println(list.last { it % 2 == 10 })  //java.util.NoSuchElementException: List contains no element matching the predicate
 println(list.lastIndexOf(5))
 println(list.lastOrNull { it % 2 == 10 })

 println(list.single { it % 6 == 5 })
 //println(list.single { it % 2 == 0 })  //java.lang.IllegalArgumentException: Collection contains more than one matching element
 println(list.singleOrNull() { it % 5 == 10 })

版权声明:本文为Amethyst128原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。