关于集合操作中异常: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 })
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值