gpt4 book ai didi

Java对重复值的数组进行排序

转载 作者:行者123 更新时间:2023-12-01 07:48:33 25 4
gpt4 key购买 nike

我有两个数组,一个是日期,另一个是金额。我想做的是,如果有相同日期的记录,我将增加金额,而不是在日期中添加另一个新项目。

这是代码:

for (int i = 0; i < tlist.size(); i++) {
Log.d("Dates", tlist.get(i).getTransactionDate());
Log.d("Amt", String.valueOf(tlist.get(i).getTransactionAmt()));
if(i == tlist.size()-1 || !tlist.get(i).getTransactionDate().equals(tlist.get(i+1).getTransactionDate()))
{
dates[i] = tlist.get(i).getTransactionDate();
totals[i] = tlist.get(i).getTransactionAmt();
}else{
totals[i] += tlist.get(i).getTransactionAmt();
}
}

示例数据:

Dates: 06/05/2017
Amt: 20.0
Dates: 10/05/2017
Amt: 10.8
Dates: 15/05/2017
Amt: 12.0
Dates: 15/05/2017
Amt: 5.0

我想要实现的目标:

Dates: 06/05/2017
Amt: 20.0
Dates: 10/05/2017
Amt: 10.8
Dates: 15/05/2017
Amt: 17.0

当我尝试将其绘制在图表上时(我直接使用日期和总计数组中的项目进行绘制),这是我得到的:

Dates: 06/05/2017
Amt: 20.0
Dates: 10/05/2017
Amt: 10.8
Dates: (No label but have amount, this one supposed to be 15/05/2017)
Amt: 12.0
Dates: 15/05/2017
Amt: 0.0

for (int j = 0; j < totals.length; j++) {
// This part plotting the line on the chart
detailSeries.add(j, totals[j]);
// This part setting the value at x-axis
multiRenderer.addXTextLabel(j, dates[j]);
}

有什么想法吗?

编辑

我尝试这样做,但出现索引越界异常。我猜是因为我在 if 条件下是+1:

if(!tlist.get(i).getTransactionDate().equals(tlist.get(i+1).getTransactionDate())) {
dates[i] = tlist.get(i).getTransactionDate();
amt = tlist.get(i).getTransactionAmt();
if (tlist.size()-2 == i)
{
dates[i] = tlist.get(i+1).getTransactionDate();
amt = tlist.get(i+1).getTransactionAmt();
}
}else{
amt = tlist.get(i).getTransactionAmt() + tlist.get(i+1).getTransactionAmt();
}
totals[i] = amt;

最佳答案

andih 几乎做到了。在这里,我提供了另一个用 Java Lambda 编写的版本。它做同样的事情。

Map<Date, Double> map = new HashMap<Date, Double>();
for (int i = 0; i < tlist.size(); i++) {
Log.d("Dates", tlist.get(i).getTransactionDate());
Log.d("Amt", String.valueOf(tlist.get(i).getTransactionAmt()));
Transaction tx = tlist.get(i);
map.computeIfPresent(tx.getTransactionDate(), (key, oldVal) -> tx.getTransactionAmt() + oldVal);
map.computeIfAbsent(tx.getTransactionDate(), key -> tx.getTransactionAmt());
}

根据 Aarjav 的建议,这是我的较短版本的较短版本。

map.compute(tx.date(), (k, v) -> v == null ? tx.amt() : v + tx.amt())

用于绘图:

int counter = 0;
for (Date k: map.keySet()) {
// This part plotting the line on the chart
detailSeries.add(counter, map.get(k));
// This part setting the value at x-axis
multiRenderer.addXTextLabel(counter, map.get(k));
counter++;
}

关于Java对重复值的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43948507/

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