Java流如果没有值则返回0。

huangapple go评论58阅读模式
英文:

Java stream return 0 if no value

问题

对象结构

账户
  金额
      浮点值;

实际上,我这样获得总和

double sum = accounts.stream()
  .filter(x -> x.getBalanceType().equals("120") || x.getBalanceType().equals("120+"))
  .collect(toList()).stream()
  .mapToDouble(y -> y.getAmount().getValue()).sum();

如果没有值,是否有一种方法可以返回0?

英文:

Structure of object

Account
  Money amount
      Float value;

Actually I get sum like that

double sum = accounts.stream()
  .filter(x -> x.getBalanceType().equals("120") || x.getBalanceType().equals("120+"))
  .collect(toList()).stream()
  .mapToDouble(y -> y.getAmount().getValue()).sum();

If there is not value, it's there a way to return 0 if there is no value

答案1

得分: 2

为什么您要收集然后再次流式传输?如果列表为空,流不会执行任何操作。

一个空列表将自动返回0;

英文:

Why are you collecting and then streaming again? If the list is empty stream wont do anything

double sum = accounts.stream()
       .filter(x -> x.getBalanceType().equals("120") || x.getBalanceType().equals("120+"))
       .mapToDouble(y -> y.getAmount().getValue())
       .sum();

An empty list will automatically return 0;

答案2

得分: 1

你可以使用条件运算符,在值不存在时,可以在条件运算符中返回0。

你可以将你的映射行更改为:

.mapToDouble(y -> y.getAmount().getValue() != null ? y.getAmount().getValue() : 0);
英文:

You can use the conditional operator, if the value is not present, you can return 0 in conditional operator.

You can change your map line as

.mapToDouble(y -> y.getAmount().getValue() != null ? y.getAmount().getValue() : 0);

huangapple
  • 本文由 发表于 2020年7月30日 01:06:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63158849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定