当前在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语法来执行相同的任务?
答案 0 :(得分:1)
选项1
我认为这是最清晰的方法,利用Optional
API:
def sampleList = [1, 2]
def element = Optional.ofNullable(sampleList.find{it==3}).orElseThrow{new IllegalStateException('Element not found!')}
选项2
我认为这不是很好,但是您可以从闭包中调用throw
,并使用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)