【问题标题】:How do i get the sum of values of an Object Array :java8我如何获得对象数组的值的总和:java8
【发布时间】:2017-05-13 17:02:32
【问题描述】:

在变量“a”中,我创建了一个double 数组,在“maxA”中,我得到了值的总和。现在在变量“b”中,我创建了一个具有双值的对象数组,现在我想使用stream 值来获得这些值的总和。感谢帮助

  double[] a = new double[] {3.0,1.0};
  double maxA = Arrays.stream(a).sum();

  ObjectWithDoubleValue  o1 = new  ObjectWithDoubleValue (3.0);
  ObjectWithDoubleValue  o2 = new  ObjectWithDoubleValue (1.0);
  ObjectArray[] b = {o1 , o2};
  double maxB = ?;

【问题讨论】:

  • 如何从对象中获取值?可能类似于Arrays.stream(b).map(o -> o.getValue()).sum();
  • 我想ObjectWithDoubleValue[] b = {o1 , o2}; 是你想要的,而不是ObjectArray[] b = {o1 , o2};
  • for (ObjectArray actualO : b){ max += actualO.getValue(); }

标签: java arrays object functional-programming java-stream


【解决方案1】:

使用mapToDouble,它将返回一个DoubleStream,并使用你的类的getter函数从你的对象中获取价值并最终应用sum

Arrays.stream(aa).mapToDouble(ObjectWithDoubleValue::getValue).sum()

getValue 是您班级的 getter 函数

class ObjectWithDoubleValue{
    double a;
    public double getValue(){
        return a;
    }
}

样本

ObjectWithDoubleValue a1= new ObjectWithDoubleValue();
a1.a=3.0;

ObjectWithDoubleValue a2= new ObjectWithDoubleValue();
a2.a=3.0;
ObjectWithDoubleValue[] aa={a1,a2};
System.out.println(Arrays.stream(aa).mapToDouble(ObjectWithDoubleValue::getValue).sum());

输出:

6.0

【讨论】:

  • 是的,这是解决我问题的完美解决方案,我非常感谢,并向大家道歉这是我的第一篇文章,我不知道如何在这个网站上做好格式。
  • @Gotti92 我很高兴能帮上忙,编码愉快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多