更新Map值的有效方法

时间:2016-03-18 15:22:11

标签: java optimization collections

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

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

要求是对&#34;值&#34;执行基本算术运算(加/减)。从Key1中为每个记录添加结果值到Key2(在单个事务中)。应保持交易的顺序。 生成的映射应具有累积事务值。

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

2 个答案:

答案 0 :(得分:0)

// map1 and map2 are your two existing maps
Map<Key, Value> resultMap = new Map<Key, Value>();

for (Map.Entry<Key, Value> entry : map1.entrySet()) {
    resultMap.put(entry.getKey(), entry.getValue() + map2.get(entry.getKey()));
}

答案 1 :(得分:0)

您有一个交易清单。让我们用一个名为

的类来表示一个事务
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}"
}