【问题标题】:How to handle extra value in Java Streams?如何处理 Java Streams 中的额外价值?
【发布时间】:2017-12-27 17:58:47
【问题描述】:

我有以下 2 个对象

Product       ProductInventory
-type         -Product
-price        -quantity  
              -country

我需要通过遍历ProductInventory 的列表来找到最便宜的。步骤是;

  1. 如果product.type == input_typequantity > input_quantity
  2. totalPrice = product.price * input_quantity
  3. 如果country != input_country 那么totalPrice = totalPrice + input_tax
  4. totalPrice 从最小值到最大值对记录进行排序
  5. 获取第一条记录并映射到新对象(国家、剩余数量、总价)

我不知道如何处理第 2 步,我需要生成总价,但是如何在流中创建和使用该字段?

【问题讨论】:

  • 你有totalPrice值,它不能存储在任何地方,为什么不将该值添加到ProductInventory
  • 你使用了包装类吗?还是直接插入库存类?
  • 我正在尝试将它插入到包装类中,因为您知道 productInventory 有不同的用途。

标签: java lambda java-stream


【解决方案1】:

使用ProductInventory 中声明的totalPrice 字段,您可以执行以下操作;

private Optional<FinalEntity> doLogic(String inputCountry, String inputType, Integer inputQuantity, Integer inputTax) {
    return Stream.of(new Inventory(new Product("cola", 15), "germany", 1000))
            .filter(inv -> inv.getProduct().getType().equals(inputType) && inv.getQuantity() > inputQuantity)
            .peek(inv -> {
                Integer tax = inv.getCountry().equals(inputCountry) ? 0 : inputTax;
                inv.setTotalPrice((inv.getProduct().getPrice() * inputQuantity) + tax);
            })
            .sorted(Comparator.comparing(Inventory::getTotalPrice))
            .findFirst()
            .map(Util::mapToFinalEntity);
}

在哪里

public class Product {

    String type;
    Integer price;

    // getters, setters, constructors
}

public class Inventory {

    Product product;
    String country;
    Integer quantity;
    Integer totalPrice;

    // getters, setters, and constructors
}

结果值要么是Optional.empty(),要么你将得到最终实体格式的结果值,我跳过了最后一个map to new object (country, quantity remaining, total price),这是一个简单的步骤。

如果您不希望在 Inventory 中包含此字段,您可以在其之上创建一个包含 totalPrice 的包装类,并从流开头的清单映射到它。

【讨论】:

  • 为什么不用map 而不是做作的peek
  • @apophis 可以使用映射,认为可能存在重复键,您必须考虑这种情况。问题是要求有一个带有总价格值的 lambda 解决方案的单个流,我的答案就是这样。
  • 如果Stream 中的对象发生了变异,@apophis using peek必需的。在这种情况下使用 map 会破坏方法的约定并导致 UB。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多