gpt4 book ai didi

java - 更新Map值的有效方法

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:19 25 4
gpt4 key购买 nike

我们有一个包含超过千万条记录的交易明细的数组

Key1    Key2    Value
-----------------------
A B <value>
B C <value>
D A <value>
...
...

要求是对每个记录的 Key1 中的“值”执行基本算术运算(加/减),并将结果值添加到 Key2(在单个事务中)。应当维护交易秩序。生成的 map 应具有累积交易值。

Key     Result
A <result>
B <result>
C <result>
...
...

请针对这种情况提出有效的解决方案。

编辑

很抱歉没有在之前的问题中明确说明这一点。

Sample data:
------------

Row1 -> A,B,Add,10.0
Row2 -> C,D,Subtract,20.0
Row3 -> D,B,Add,50.0
Row4 -> B,X,Subtract,30.0

Initial Map:
------------
A 1000
B 1000
C 1000
D 1000
X 1000

Row 1 => 10.0 to be subtracted from B and added to A (B:990 - A:1010)
Row 2 => 20.0 to be subtracted from C and added to D (C:980 - D:1020)
Row 3 => 50.0 to be subtracted from B and added to D (B:940 - D:1070)
Row 4 => 30.0 to be subtracted from B and added to X (B:910 - X:1030)

Resulting Map:
--------------
A 1010
B 910
C 980
D 1070
X 1030

最佳答案

您有一个交易列表。让我们用自己的类来表示一项交易

public class Transaction {

private String target;
private String source;
private String operation;
private int amount;

public Transaction(String target, String source, String operation, int amount) {
this.target = target;
this.source = source;
this.operation = operation;
this.amount = amount;
}

// + getters

}

source将代表交易的来源和 target目标。在 "Add" 的情况下操作,将由 amount 推导出来源并且目标将增加金额。如果操作是"Subtract" ,交易被撤销。

然后,给定 Map<String, Integer> map保存初始值,我们可以循环这些交易并进行计算。在每个过程中,我们只需从源中减去金额并将其添加到目标中(在 "Subtract" 的情况下,金额为负,因此交易被有效逆转)。

public static void main(String[] args) {
// set-up sample data
Map<String, Integer> map = new HashMap<>();
for (String s : Arrays.asList("A", "B", "C", "D", "X")) {
map.put(s, 1000);
}
List<Transaction> transactions = Arrays.asList(
new Transaction("A","B","Add",10),
new Transaction("C","D","Subtract",20),
new Transaction("D","B","Add",50),
new Transaction("B","X","Subtract",30)
);

// implement the transactions
for (Transaction t : transactions) {
final int amount = t.getOperation().equals("Add") ? t.getAmount() : -t.getAmount();
map.put(t.getSource(), map.get(t.getSource()) - amount);
map.put(t.getTarget(), map.get(t.getTarget()) + amount);
}

System.out.println(map); // prints "{A=1010, B=910, C=980, D=1070, X=1030}"
}

关于java - 更新Map值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36088158/

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