0

I've been searching for a way to do this and have come up empty and hoping someone may have an idea. I have an arrayList that is storing objects such as

{addToList, firstName, lastName, 1.0} 
{addToList, firstName, lastName, 0.5} 
{addToList, firstName, lastName, 0.5} 
{addToList, firstName, lastName, 1.5} 

I need a way to add the values of the double amount from all of the objects, so I can get an output of

total amount is $4.5

Any help is appreciated =)

6
  • do you have a getter in that class for the double? Commented May 22, 2017 at 16:48
  • what did you tried? Commented May 22, 2017 at 16:53
  • @ChandlerBing yes I do have a getter Commented May 22, 2017 at 16:56
  • 2
    @Newb2Java then see Amonie's answer, does exactly what you want. Commented May 22, 2017 at 16:58
  • 1
    It is ok. If you can add your code we can get an idea about what you are trying and we can point reasons to errors. Commented May 22, 2017 at 17:05

1 Answer 1

3

here is one solution to accomplishing your task:

double sum = myList.stream().mapToDouble(ObjectType::getAmount).sum();
System.out.println("total amount is  $" + sum);

where ObjectType is your class name and getAmount is the getter for the price within each object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.