Java中如何从Map对象获取ManufacturerPriceCode指定字段值
问题解决:从Map中正确获取ManufacturerPriceCodes的字段值
错误原因分析
你当前代码里的循环逻辑完全错误:
for (ItemPriceCode ipcs : itemPriceCodes) { ipcs.setManufacturerPriceCode(ipcToMFPNameMap.getClass().getName()); }
这里调用ipcToMFPNameMap.getClass().getName()获取的是Map对象自身的类名称(也就是java.util.HashMap),根本不是ManufacturerPriceCodes对象里的业务字段值,这就是你得到错误结果的核心原因。
你后续尝试的代码里存在变量未定义的问题:priceCode没有被赋值,应该用当前循环的ItemPriceCode实例的价格码作为键去Map中取值。
修正后的代码
将循环部分替换为以下逻辑,同时增加空值判断避免空指针异常:
private Item getItemManufacturerPriceCodes(Item item) { List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes(); List<String> priceCodeList = new ArrayList<String>(); for (ItemPriceCode ipc : itemPriceCodes) { priceCodeList.add(ipc.getPriceCode()); } List<ManufacturerPriceCodes> mpc = manufacturerPriceCodesRepository .findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(), priceCodeList, NOT_DELETED); // 把查询结果转成以priceCode为键的Map Map<String, ManufacturerPriceCodes> ipcToMFPNameMap = mpc.stream() .collect(Collectors.toMap(ManufacturerPriceCodes::getPriceCode, Function.identity())); // 循环为每个ItemPriceCode设置对应的ManufacturerPriceCode值 for (ItemPriceCode ipcs : itemPriceCodes) { // 获取当前ItemPriceCode的价格码作为键 String currentPriceCode = ipcs.getPriceCode(); // 从Map中取出对应的ManufacturerPriceCodes对象 ManufacturerPriceCodes manufacturerPriceCodes = ipcToMFPNameMap.get(currentPriceCode); // 非空判断,避免空指针 if (manufacturerPriceCodes != null) { // 调用getName()获取你需要的字段值,这里根据实际字段名调整 ipcs.setManufacturerPriceCode(manufacturerPriceCodes.getName()); } else { // 可选:处理找不到对应数据的情况,比如设置默认值 ipcs.setManufacturerPriceCode("无匹配值"); } } item.getItemPriceCodes().removeIf(ipcs -> DELETED.equals(ipcs.getRecordDeleted())); return item; }
关键说明
- 用
ipcs.getPriceCode()获取当前循环项的价格码,作为Map的键去查找对应的ManufacturerPriceCodes对象 - 增加非空判断,防止查询结果中没有匹配的价格码导致
NullPointerException - 调用
manufacturerPriceCodes.getName()获取你需要的字段值(如果目标字段不是name,替换为对应的getter方法即可)
内容的提问来源于stack exchange,提问作者user20714961
相关产品推荐
相关产品推荐

