gpt4 book ai didi

java 8 Stream - 如何在映射后获取原始对象引用

转载 作者:行者123 更新时间:2023-12-01 18:20:26 25 4
gpt4 key购买 nike

是否可以使用 Java 8 流来简单地编写以下代码?

代码:-

private double calculateBCMMatrixCostForAnalyte(Long startingMaterialId) {

double bcmMatrixCost = 0;

StartingMaterialMatrix smm = startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId);

if (smm.getBlending1MatrixConcentration() != null) {
bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId()) * smm.getBlending1MatrixConcentration()) / 1000000f;
}

if (smm.getBlending2MatrixConcentration() != null) {
bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending2Matrix().getId() * smm.getBlending2MatrixConcentration())) / 1000000f;
}

return Precision.round(bcmMatrixCost, 4);
}

我尝试了类似下面的内容

    Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
.filter(smm -> smm.getBlending1MatrixConcentration() != null)
.mapToDouble(smm -> priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f);

但在此之后,我将不再有任何对原始“smm”对象的引用来进行进一步检查。

最佳答案

这确实不可读,但在这里

public double streamWay(Long startingMaterialId) {

return Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
.map(Stream::of)
.flatMapToDouble(smmStream ->
DoubleStream.concat(
smmStream.filter(smm -> smm.getBlending1MatrixConcentration() != null)
.mapToDouble(smm -> priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f),
smmStream.filter(smm -> smm.getBlending1MatrixConcentration() != null)
.mapToDouble(smm -> priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId() * smm.getBlending2MatrixConcentration()) / 1000000f)
)).sum();


}

关于java 8 Stream - 如何在映射后获取原始对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60301304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com