[英]Efficient way to use to loop through the list in Java
I have a function logic that will fail the process if there are price dtos that have null item & current price properties.如果有具有 null 项目和当前价格属性的价格 dto,我有一个 function 逻辑将失败该过程。
I was wondering if there's a more efficient or cleaner way to do this in Java.我想知道在 Java 中是否有更有效或更清洁的方法来执行此操作。 In streams or any other.
在溪流或其他任何地方。
Here is my current code:这是我当前的代码:
List<PriceDto> priceDtoList = thisIsAClass.getPriceDtos();
for (PriceDto priceDto: priceDtoList) {
if (priceDto.getItem() == null && priceDto.getCurrentPrice() == null)
{
thisIsAnotherClass.failTheProcess();
break;
}
}
thisIsAnotherClass.anotherProcess();
Thank you in advance for your help!预先感谢您的帮助!
The more common way in newer version Java would be to use findFirst
or findAny
.较新版本 Java 中更常见的方法是使用
findFirst
或findAny
。
For example,例如,
List<PriceDto> priceDtoList = thisIsAClass.getPriceDtos();
Optional<PriceDto> result = list
.stream()
.filter(dto -> dto.getItem() ==null && dto.getCurrentPrice() == null)
.findAny();
if(result.isPresent()) {
thisIsAnotherClass.failTheProcess();
}
thisIsAnotherClass.continueTheProcess();
If you have a lot of data in the list you could also look at adding a .parallel()
call to the stream to improve overall performance of the search.如果列表中有大量数据,您还可以考虑将
.parallel()
调用添加到 stream 以提高搜索的整体性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.