假设我有一个对象POJO样式,并且对于它的某些属性,我必须检查是否等于特定值。如果是这样,我必须将此属性添加到列表中并引发异常(如果其中一个属性等于特定值,则仅抛出一次)。有没有比这更好的方法呢?
// pseudocode
List<String> list = new ArrayList<String>();
boolean haveToThrowException = false;
if (object.getAttributeA().equals(“0”) {
list.add(object.getAttributeA());
haveToThrowException = true;
}
if (object.getAttributeB().equals(“0”) {
list.add(object.getAttributeB());
haveToThrowException = true;
}
if (object.getAttributeC().equals(“0”) {
list.add(object.getAttributeC());
haveToThrowException = true;
}//and so on
if (haveToThrownException) {
throw new Exception(list.toString());
}
您可以这样做:
List<String> list =
Stream.of(object.getAttributeA(), object.getAttributeB(), object.getAttributeC())
.filter("0"::equals)
.collect(toList());
if (!list.isEmpty()) {
throw new Exception(list.toString());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句