John Mulaney
John Mulaney

Reputation: 109

Getting the Total Value from Elements in a Map

I'm trying to make a method called getValueForActivity that needs to go through a Map<String, Activity> then for each Activity inside that map, go through a Map<String, Expense> and get the sum of all the expenses. It also needs to make sure that I'm inside one special type of user.

public ArrayList<Double> getValueForActivity(){
   ArrayList<Double> list = new ArrayList<Double>();
   for(Activity a:this.allActiv.values()){ //allActiv has all the activities on the system.
       double totalAct = 0;
       for(Expense e: this.expenses.values()){ //this.expenses has all the expenses on the system.
           if(this.userId.equals(e.getCustomerId())){ // this checks the user, doesn't matter
                if(e.getActivity().equals(a)){
                    totalAct += e.getExpenseValue();
                }
           }
       }
       list.add(totalAct);
   }
   return list;
}

At the moment this is printing an Array with the right values but with 1 error. It shifted the values to the right, so where the first should be 168.0 it's 0.0 and the second is 168.0, and so on.

What I'm looking for is to get a solution that not only allows me to print the total value for each Activity but that also prints the name of the activity before the respective total value. The method to get the Activity name is just getName(). The ArrayList is only allowing me to either have the value or the Activity.

Upvotes: 0

Views: 58

Answers (1)

shmosel
shmosel

Reputation: 50776

Return a map of values with the activity name as key:

public Map<String, Double> getValueForActivity() {
    return this.allActiv.values()
            .stream()
            .collect(Collectors.toMap(Activity::getName, this::sumExpenses));
}

private double sumExpenses(Activity activity) {
    return this.expenses.values()
            .stream()
            .filter(e -> this.userId.equals(e.getCustomerId()))
            .filter(e -> e.getActivity().equals(activity))
            .mapToDouble(Expense::getExpenseValue)
            .sum();
}

Upvotes: 3

Related Questions