可以优化 if (list == null || list.isEmpty())吗

时间: 2024-05-14 20:19:55 浏览: 9
可以使用 Java 8 引入的 Optional 类型来优化 if (list == null || list.isEmpty()) 的写法,示例如下: ```java Optional<List<String>> optionalList = Optional.ofNullable(list); if (optionalList.isPresent() && !optionalList.get().isEmpty()) { // list 不为空且不为空列表 } ``` 上述代码中,首先使用 Optional.ofNullable() 方法将 list 转换为 Optional 对象,然后使用 isPresent() 方法判断 Optional 对象是否存在值,最后使用 get() 方法获取 Optional 对象的值,并判断是否为空列表。这样可以避免空指针异常,并且代码更加简洁明了。不过需要注意的是,过度使用 Optional 也可能会导致代码变得复杂,因此需要根据具体情况灵活使用。
相关问题

List<TrDevice> trDeviceList = trDeviceService.listDeviceByName(devName); if (trDeviceList == null || trDeviceList.isEmpty() || trDeviceList.size()<1) { resUploadFileVos.add(new ResUploadFileVo(row, 2, "", "设备名称查询无数据")); continue; } 这块代码有没有bug

这段代码看起来没有明显的 bug。它首先通过设备名称查询设备列表,如果查询结果为空或者设备列表为空,则会将一个 ResUploadFileVo 对象添加到 resUploadFileVos 列表中,并继续执行下一次循环。如果查询结果不为空,则说明查询到了设备,可以进行后续操作。不过,如果你有更多的上下文信息或者具体的需求,可以进一步分析代码是否满足你的要求。

优化这段代码,复杂度降低到15以下:public AjaxResult selectDeviceByCode(HttpServletRequest request,@RequestParam Map<String, Object> form) { List<HashMap<String, Object>> list = facilityService.selectDeviceByCode(form); // 判断list是否为空 if (list == null || list.isEmpty()) { return AjaxResult.error("此设备不存在,请联系管理员"); } else { if (list.get(0).get(guestIdDetail) != null) { Attention attention = new Attention(); //设备绑定人 long beGuestId = Long.valueOf(list.get(0).get(guestIdDetail).toString()); attention.setBeGuestId(beGuestId); // 当前登入人 Long guestId = getAPPUserId(request); attention.setGuestId(guestId); //判断当前登入人与设备绑定人是否为同一人 if (attention.getGuestId().equals(beGuestId)) { return error("无法绑定自己的设备"); } // 判断是否关注亲友 List<Attention> attentionList = attentionService.selAttention(attention); if (attentionList != null && !attentionList.isEmpty()) { Attention attentionDetail = attentionList.get(0); if (attentionDetail.getOverTime() != null) { return error("该设备已被亲友绑定,且您已关注亲友"); } return error("已提交关注申请"); } } return success(list.get(0)); } }

这段代码的复杂度较高,需要进行一些优化,可以采用以下方法: 1. 将 if-else 结构中的 if 语句提取出来,避免嵌套过深; 2. 对于一些重复的变量和表达式,进行提取和复用; 3. 将一些判断条件合并,避免重复判断。 以下是优化后的代码: public AjaxResult selectDeviceByCode(HttpServletRequest request, @RequestParam Map<String, Object> form) { List<HashMap<String, Object>> list = facilityService.selectDeviceByCode(form); // 判断list是否为空 if (list == null || list.isEmpty()) { return AjaxResult.error("此设备不存在,请联系管理员"); } // 获取设备绑定人 Object guestIdDetail = list.get(0).get("guestIdDetail"); if (guestIdDetail != null) { Attention attention = new Attention(); //设备绑定人 long beGuestId = Long.valueOf(guestIdDetail.toString()); attention.setBeGuestId(beGuestId); // 当前登入人 Long guestId = getAPPUserId(request); attention.setGuestId(guestId); //判断当前登入人与设备绑定人是否为同一人 if (attention.getGuestId().equals(beGuestId)) { return error("无法绑定自己的设备"); } // 判断是否关注亲友 List<Attention> attentionList = attentionService.selAttention(attention); if (attentionList != null && !attentionList.isEmpty()) { Attention attentionDetail = attentionList.get(0); if (attentionDetail.getOverTime() != null) { return error("该设备已被亲友绑定,且您已关注亲友"); } return error("已提交关注申请"); } } return success(list.get(0)); } 通过将 if-else 结构中的 if 语句提取出来,避免嵌套过深,将一些重复的变量和表达式提取和复用,将一些判断条件合并,可以将代码的复杂度降低到15以下,使代码更加简洁和易于维护。

相关推荐

private void checkGoodsStock(Goods goods, Integer buyNum) { //商品为现货商品,判断商品现货可用库存 if (GoodsSaleType.SPOT == GoodsSaleType.findSaleType(goods.getSaleType())) { //单个商品、意向商品 if (GoodsShelveType.SINGLE.getShelveType() == goods.getShelveType() || GoodsShelveType.INTENTION.getShelveType() == goods.getShelveType()) { BaseGoods baseGoods = iBaseGoodsService.getOne(Wrappers.<BaseGoods>lambdaQuery().in(BaseGoods::getModel, goods.getModel()).last("for update")); if (buyNum > baseGoods.getSpotOccupyStock()) { throw new ServiceException(ErrorMessage.STOCK_ERROR); } } //组合商品 if (GoodsShelveType.COMBINATION.getShelveType() == goods.getShelveType()) { //查询组合商品子商品信息 List<GoodsChilds> goodsChildsList = goodsChildsService.lambdaQuery().eq(GoodsChilds::getParentId, goods.getId()).eq(GoodsChilds::getIsGift, 0).list(); if (CollectionUtils.isEmpty(goodsChildsList)) { throw new ServiceException("组合商品子商品信息为空"); } //子商品所有商品型号 List<String> goodsChildsModelList = goodsChildsList.stream().map(GoodsChilds::getModel).collect(Collectors.toList()); List<BaseGoods> baseGoodsList = iBaseGoodsService.list(Wrappers.<BaseGoods>lambdaQuery().in(BaseGoods::getModel, goodsChildsModelList).last("for update")); Map<String, BaseGoods> baseGoodsMap = AppUtils.listToMap(baseGoodsList, BaseGoods::getModel); for (GoodsChilds goodsChilds : goodsChildsList) { BaseGoods baseGoods = baseGoodsMap.get(goodsChilds.getModel()); if (baseGoods == null) { throw new ServiceException("商品型号不存在"); } //子商品总购买数 Integer goodsChildsBuyNum = goodsChilds.getNumberCoefficient().multiply(new BigDecimal(buyNum)).intValue(); if (goodsChildsBuyNum > baseGoods.getSpotOccupyStock()) { throw new ServiceException(ErrorMessage.STOCK_ERROR); } } } } //非现货商品,判断上架库存 if (GoodsSaleType.SPOT != GoodsSaleType.findSaleType(goods.getSaleType()) && buyNum > goods.getStock()) { throw new ServiceException(ErrorMessage.STOCK_ERROR); } }优化该段代码

List<DataPermissionSchemaEo> dataPermissionSchemaEoList = comDataComponent.getDataPermissionSchemaList(); List<SchemaRowRuleEo> schemaRowRuleList = comDataComponent.getSchemaRowRuleList(); List<SchemaColumnRuleEo> schemaColumnRuleList = comDataComponent.getSchemaColumnRuleList(); //设置行权限 根据用户id和用户组织去获取 List<SchemaRowRule> userRowRuleList = schemaRowRuleList.stream() .filter(schemaRowRuleEo -> { List<String> userList = JSONObject.parseArray(schemaRowRuleEo.getRowPermissionUserList(), String.class); List<String> orgList = JSONObject.parseArray(schemaRowRuleEo.getRowPermissionOrgList(), String.class); return userList.contains(userUid) || orgList.contains(orgCode) || userList.contains(WILDCARD) || orgList.contains(WILDCARD); }) .map(schemaRowRuleEo -> { SchemaRowRule schemaRowRule = new SchemaRowRule(); BeanUtils.copyProperties(schemaRowRuleEo, schemaRowRule); return schemaRowRule; }) .collect(Collectors.toList());List<SchemaColumnRule> userColumnRuleList = schemaColumnRuleList.stream() .filter(rule -> { List<String> userList = Optional.ofNullable(rule.getColumnPermissionUserList()) .map(userListStr -> JSONObject.parseArray(userListStr, String.class)) .orElse(Collections.emptyList()); List<String> orgList = Optional.ofNullable(rule.getColumnPermissionOrgList()) .map(orgListStr -> JSONObject.parseArray(orgListStr, String.class)) .orElse(Collections.emptyList()); return userList.contains(userUid) || orgList.contains(orgCode) || userList.contains(WILDCARD) || orgList.contains(WILDCARD); }) .map(rule -> { SchemaColumnRule columnRule = new SchemaColumnRule(); BeanUtils.copyProperties(rule, columnRule); return columnRule; }) .collect(Collectors.toList()); List<DataPermissionSchema> dataPermissionSchemaList = dataPermissionSchemaEoList.stream().map(dataPermissionSchemaEo -> { List<SchemaRowRule> schemaRowRules = userRowRuleList.stream() .filter(schemaRule -> dataPermissionSchemaEo.getDatabaseCode().equals(schemaRule.getDatabaseCode()) && dataPermissionSchemaEo.getSchemaCode().equals(schemaRule.getSchemaCode())) .collect(Collectors.toList()); List<SchemaColumnRule> schemaColumnRules = userColumnRuleList.stream() .filter(schemaRule -> dataPermissionSchemaEo.getDatabaseCode().equals(schemaRule.getDatabaseCode()) && dataPermissionSchemaEo.getSchemaCode().equals(schemaRule.getSchemaCode())) .collect(Collectors.toList()); if(!schemaRowRules.isEmpty() || !schemaColumnRules.isEmpty()) { DataPermissionSchema dataPermissionSchema = new DataPermissionSchema(); dataPermissionSchema.setDatabaseCode(dataPermissionSchemaEo.getDatabaseCode()); dataPermissionSchema.setSchemaCode(dataPermissionSchemaEo.getSchemaCode()); dataPermissionSchema.setSchemaRowRuleList(schemaRowRules); dataPermissionSchema.setSchemaColumnRuleList(schemaColumnRules); return dataPermissionSchema; } return null; }).filter(Objects::nonNull).collect(Collectors.toList());把这段代码改造成每个用户拥有的行权限和列权限

@Override public SdFact checkCodeByLevel2Id(SdFact et) { if(et.getClassifyId() == null || et.getClassifyId().length() == 0) { throw Exp.instance(BizCode.biz_error, "事实表所属类别不能为空!"); } if(et.getTableCode() == null || et.getTableCode().length() == 0) { throw Exp.instance(BizCode.biz_error, "事实表编码不能为空!"); } SdClassify classify = classifyService.getById(et.getClassifyId()); if(classify.getLevel2Id() == null || classify.getLevel2Id().length() == 0) { throw Exp.instance(BizCode.biz_error, "事实表所属类别不能是一级或者二级!"); } QueryWrapper<SdClassify> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("level2_id",classify.getLevel2Id()); List<SdClassify> classifies = classifyService.getMapper().selectList(queryWrapper); if(CollectionUtils.isEmpty(classifies)) { throw Exp.instance(BizCode.biz_error, "事实表所属类别不能是一级或者二级!"); } List<String> classifyIds = classifies.stream().map(o -> o.getId()).collect(Collectors.toList()); QueryWrapper<SdFact> factQueryWrapper = new QueryWrapper<>(); factQueryWrapper.in("classify_id",classifyIds); factQueryWrapper.eq("table_code",et.getTableCode()); if(et.getId() != null) { factQueryWrapper.ne("id",et.getId()); } List<SdFact> facts = this.getMapper().selectList(factQueryWrapper); if(!CollectionUtils.isEmpty(facts)) { throw Exp.instance(BizCode.biz_error, "事实表编码在同一二级分类下不能重复!"); } return et; },多加一个功能,根据表格编码和子分类ID列表查询数据库中是否存在相同分类下的表格编码,若存在,则抛出异常;

public void setupLoadReaderTask() { if (task != null) { task.cancel(true); } if (RfApplication.readers == null) { RfApplication.readers = new Readers(this, ENUM_TRANSPORT.ALL); } task = new AsyncTask<Void, String, String>() { @Override protected synchronized String doInBackground(Void... voids) { InvalidUsageException hj = null; if (isCancelled()) { return null; } if (RfApplication.readers == null) { return null; } publishProgress("readers.GetAvailableRFIDReaderList()"); if (isCancelled()) { return null; } List<ReaderDevice> list = null; list = RfApplication.readers.GetAvailableRFIDReaderList(); if (hj != null){ RfApplication.readers.Dispose(); RfApplication.readers = null; if (RfApplication.readers == null) { RfApplication.readers = new Readers(getApplicationContext(), ENUM_TRANSPORT.BLUETOOTH); } } if (list == null || list.isEmpty()) { return null; } publishProgress("device.getRFIDReader()"); if (isCancelled()) { return null; } for (ReaderDevice readerDevice : list) { RfApplication.device = readerDevice; RfApplication.deviceName = readerDevice.getName(); Log.d("deviceName", readerDevice.getName()); RfApplication.reader = RfApplication.device.getRFIDReader(); // Log.d("地址:",readerDevice.getAddress()); if (RfApplication.reader.isConnected()) { return null; } publishProgress("reader.connect()"); if (isCancelled()) { return null; } try { RfApplication.reader.connect(); isStarted = true; configureReader(); } catch (InvalidUsageException | OperationFailureException e) { } if (RfApplication.reader.isConnected()) { break; } } if (!RfApplication.reader.isConnected()) { return null; } if (RfApplication.device.getName().startsWith("RFD8500") || RfApplication.device.getName().startsWith("RFD40")) { try { RfApplication.reader.Config.setBeeperVolume(BEEPER_VOLUME.QUIET_BEEP); RfApplication.reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.BARCODE_MODE,false); RfApplication.reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.RFID_MODE,true); } catch (InvalidUsageException | OperationFailureException e) { } } return String.format(getString(R.string.connect), RfApplication.device.getName().substring(0,RfApplication.device.getName().length()-14)); } @Override protected void onProgressUpdate(String... values) { } @Override protected void onPostExecute(String s) { if (s == null) { if (isStarted == false){ setupRetryDialog(); } } else { CustomToast.showLoad(HomeActivity.this,s,2000); } } @Override protected void onCancelled() { RfApplication.reader = null; RfApplication.readers = null; CustomToast.showToast(HomeActivity.this,getString(R.string.no_reader),2000); } }; task.execute(); }com.zebra.rfid.api3.InvalidUsageExceptionat com.ives.upcrfid_zebra.HomeActivity$12.doInBackground(HomeActivity.java:519)at com.ives.upcrfid_zebra.HomeActivity$12.doInBackground(HomeActivity.java:504)怎么解决

最新推荐

recommend-type

grpcio-1.63.0-cp38-cp38-linux_armv7l.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

SQLyog-13.1.3-0.x86Community.exe

SQLyog-13.1.3-0.x86Community
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

用Spring boot和vue写一个登录注册界面

好的,这是一个比较常见的技术问题,我可以为您提供一些参考资料和思路。首先,您可以使用Spring Boot作为后端框架来处理用户认证和注册的逻辑,比如使用Spring Security实现用户登录认证。同时,您还需要设计相应的数据模型和数据库表结构来存储用户信息。在前端方面,您可以使用Vue.js作为框架来构建登录注册页面,使用Axios来发起API请求并和后端进行交互。当然,在实现过程中,还需要考虑一些具体细节,比如数据校验、安全性和用户体验等方面。希望这些信息能够帮助到您。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

MATLAB柱状图在数据分析中的作用:从可视化到洞察

![MATLAB柱状图在数据分析中的作用:从可视化到洞察](https://img-blog.csdnimg.cn/img_convert/1a36558cefc0339f7836cca7680c0aef.png) # 1. MATLAB柱状图概述** 柱状图是一种广泛用于数据可视化的图表类型,它使用垂直条形来表示数据中不同类别或组别的值。在MATLAB中,柱状图通过`bar`函数创建,该函数接受数据向量或矩阵作为输入,并生成相应的高度条形。 柱状图的优点在于其简单性和易于理解性。它们可以快速有效地传达数据分布和组别之间的比较。此外,MATLAB提供了广泛的定制选项,允许用户调整条形颜色、
recommend-type

命名ACL和拓展ACL标准ACL的具体区别

命名ACL和标准ACL的主要区别在于匹配条件和作用范围。命名ACL可以基于协议、端口和其他条件进行匹配,并可以应用到接口、VLAN和其他范围。而标准ACL只能基于源地址进行匹配,并只能应用到接口。拓展ACL则可以基于源地址、目的地址、协议、端口和其他条件进行匹配,并可以应用到接口、VLAN和其他范围。