简体   繁体   English

Java:将两个列表相乘,它们是 Stream<BigDecimal>

[英]Java: Multiply two list which are Stream<BigDecimal>

I know my Question is a little for beginners, but in Internet I didn't find Answer, So It's good to have, I have a list which contain two value, first an Enum Type, second a big decimal Number.我知道我的问题有点适合初学者,但在互联网上我没有找到答案,所以很好,我有一个包含两个值的列表,第一个是枚举类型,第二个是大十进制数。 In my Enum Class, I have also two values related to each Enum, the first value is a string and the second is a BigDecimal.在我的 Enum 类中,我还有两个与每个 Enum 相关的值,第一个值是一个字符串,第二个是一个 BigDecimal。

Enum:枚举:

    private enum myEnumClass {
  BMW("Karl Rapp", new BigDecimal("1916")), BENZ("Carl Benz", new BigDecimal("1926")),
  private String founder;
  private BigDecimal yearOfFoundation;

List:列表:

List<CarDetails> numberOfcars = new ArrayList<>();
numberOfcars.add(new CarDetails(BMW, new BigDecimal("3")));
CarDetails.add(new Receipt(BENZ, new BigDecimal("5")));

CarDetails Class: CarDetails 类:

    class CarDetails {
  myEnumClass carCompany;
  BigDecimal amountOfCar;

I want to multiply yearOfFundation to numberOfCar for each company, so like:我想为每家公司将 yearOfFundation 乘以 numberOfCar,例如:

for BMW=1916*3;
for BENZ= 1926*5;
and then plus them: (1916*3)(1926*5);

I want to use Stream() I think it might be possible, but the problem is when I use stream I get this Datatyp: Stram, which not Allows me to use: BigDecimal.multiply(BigDecimal).我想使用 Stream() 我认为这可能是可能的,但问题是当我使用流时,我得到了这个数据类型:Stram,它不允许我使用:BigDecimal.multiply(BigDecimal)。 any idea how can I write is correctly?知道我怎么写是正确的吗? Thanks a lot!非常感谢!

Using stream and reduce , You could do something like this使用减少,你可以做这样的事情

BigDecimal res = numberOfcars
    .stream()
    .reduce(
        BigDecimal.ZERO,
        (BigDecimal acc, CarDetails c) -> acc.add(
            c.getAmountOfCar().multiply(c.getCarCompany().getYearOfFoundation())
        ),
        BigDecimal::add
    );

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM