【问题标题】:Is there a way to modify below code using java8 map有没有办法使用java8 map修改下面的代码
【发布时间】:2023-02-21 03:10:32
【问题描述】:
我是 java 8 的新手,我想使用 java 8 流映射修改我的旧版本代码,但我无法使用 java 8 映射修改下面的代码。是否可以使用 java 8.x 修改代码?
private Item getItemManufacturerPriceCodes(Item item) {
List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
for(ItemPriceCode ipc : itemPriceCodes) {
Optional<ManufacturerPriceCodes> mpc = manufacturerPriceCodesRepository.findByManufacturerIDAndPriceCodeAndRecordDeleted(item.getManufacturerID(), ipc.getPriceCode(), NOT_DELETED);
if (mpc.isPresent())
ipc.setManufacturerPriceCode(mpc.get().getName());
}
item.getItemPriceCodes()
.removeIf(ipc -> DELETED.equals(ipc.getRecordDeleted()));
return item;
}
我尝试了很多东西,但这个功能无法修改。我在上面为每个循环声明了 jpa 查询行并映射了 PriceCodes 列表,但无法获得准确的结果。这是由上述功能产生的。如何使用java 8 map stream修改以上功能,所有数据都来自数据库。我如何修改此功能。
【问题讨论】:
标签:
java
java-stream
option-type
【解决方案1】:
下面是循环部分:
itemPriceCodes.stream()
.filter(create method which take the output of manufacturerPriceCodesRepository.findByManufacturerIDAndPriceCodeAndRecordDeleted(item.getManufacturerID(), ipc.getPriceCode(), NOT_DELETED) and return boolan and call it here as
ipc -> themethod(manufacturerPriceCodesRepository.findByManufacturerIDAndPriceCodeAndRecordDeleted(item.getManufacturerID(), ipc.getPriceCode(), NOT_DELETED)))
.forEach(ipc -> ipc.setManufacturerPriceCode(mpc.get().getName()));
这里有一些资源:https://dev.java/learn/the-stream-api/
【解决方案2】:
我宁愿坚持像你提供的那样的命令式逻辑,因为原始代码中 for-loop 的主要目的是改变状态你的域对象。
这意味着您需要执行副作用通过 Stream.forEach(),根据 Stream API 文档,作为最后的手段应谨慎使用(并且由于有另一种方法,即 for-loop,因此在流上使用 forEach() 是不合理的),或者第二种方法是将存储库返回的 Optional 值具体化为集合 (这会增加内存消耗,因此我的建议还是坚持使用原始代码).
纯粹出于教育目的,这里有一个如何实现后一个选项的示例,使用 Collector toMap() 将每个 ItemPriceCode 与相应的 Optional<ManufacturerPriceCodes> 相关联。
Iterable.forEach() 和Optional.ifPresent() 的组合用于修改ItemPriceCode 实例的状态。
private Item getItemManufacturerPriceCodes(Item item) {
Map<ItemPriceCode, Optional<ManufacturerPriceCodes>> mpcList =
item.getItemPriceCodes().stream()
.collect(Collectors.toMap(
Function.identity(), // keyMapper
ipc -> foo(ipc), // valueMapper
(left, rihgt) -> left.or(() -> rihgt) // mergeFunction - both parameters are of type Optional<ManufacturerPriceCodes>, left.or(() -> rihgt) replaces `left` with `right` if the left is empty
));
mpcList.forEach((ipc, optionalMpc) ->
optionalMpc.ifPresent(mpc -> ipc.setManufacturerPriceCode(mpc.getName()))
);
item.getItemPriceCodes()
.removeIf(ipc -> DELETED.equals(ipc.getRecordDeleted()));
return item;
}
笔记: