Groovy是否有用于在集合中查找元素的专用语法,或者在未找到时抛出异常?

Groovy是否有用于在集合中查找元素的专用语法,或者在未找到时抛出异常?,groovy,Groovy,目前在Groovy中,我需要编写以下代码来实现简单逻辑: def sampleList = [1, 2] def element = sampleList.find { it == 3 } if (!element) { throw new IllegalStateException('Element not found!') } 使用Java Streams只需简单一点: def sampleList = [1, 2] sampleList.stream().filter { it

目前在Groovy中,我需要编写以下代码来实现简单逻辑:

def sampleList = [1, 2]
def element = sampleList.find { it == 3 }
if (!element) {
    throw new IllegalStateException('Element not found!')
}
使用Java Streams只需简单一点:

def sampleList = [1, 2]
sampleList.stream().filter { it == 3 }.findFirst().orElseThrow {
    new IllegalStateException('Element not found!')
}
是否有其他简洁的Groovy语法来执行相同的任务?

选项1 我认为这是最清晰的,利用了
可选的
API:

def sampleList = [1, 2]
def element = Optional.ofNullable(sampleList.find{it==3}).orElseThrow{new IllegalStateException('Element not found!')}
选项2

我不认为这很好,但是您可以从闭包中调用
抛出
,并使用elvis
?:
操作符

def sampleList = [1, 2]
def element = sampleList.find{it==3} ?: {throw new IllegalStateException('Element not found!')}()
//Alternately: ...{throw new IllegalStateException('Element not found!')}.call() to make it more readable
抛出:

Exception thrown

java.lang.IllegalStateException: Element not found!
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at ConsoleScript20$_run_closure2.doCall(ConsoleScript20:2)
    at ConsoleScript20$_run_closure2.doCall(ConsoleScript20)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at ConsoleScript20.run(ConsoleScript20:2)
    at jdk.internal.reflect.GeneratedMethodAccessor218.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
在groovy控制台中

选项3 另一个选项是将所有逻辑提取到命名闭包中:

def sampleList = [1, 2]
def tester = {list, value -> if(value in list){value} else{throw new IllegalStateException('Element not found!')}}

tester(sampleList, 3)