gpt4 book ai didi

java - 获取 map 中元素的总值(value)

转载 作者:行者123 更新时间:2023-12-01 19:53:34 32 4
gpt4 key购买 nike

我正在尝试创建一个名为 getValueForActivity 的方法需要经过Map<String, Activity>然后对于每个 Activity在该 map 内,浏览 Map<String, Expense>并得到所有费用的总和。它还需要确保我属于一种特殊类型的用户。

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;
}

目前正在打印一个具有正确值但有 1 个错误的数组。它将值向右移动,因此第一个应该是 168.0 的地方是 0.0,第二个是 168.0,依此类推。

我正在寻找的是一个解决方案,它不仅允许我打印每个 Activity 的总值(value)但这还会在相应的总值之前打印 Activity 的名称。获取Activity的方法名字只是 getName()ArrayList只允许我拥有值或 Activity .

最佳答案

返回以 Activity 名称为键的值映射:

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();
}

关于java - 获取 map 中元素的总值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50400254/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com