简体   繁体   English

我如何在 Map 中存储多个键/值<string, deque<double> &gt; 一些变量名</string,>

[英]How would I store more than one key / value in a Map<String, Deque<Double>> someVariableName

I am a beginner so please be easy on me.我是初学者,所以请放轻松。 I have to create a Stocks program that would store different 3-letter stock codes, stock prices, and purchase prices.我必须创建一个 Stocks 程序来存储不同的 3 个字母的股票代码、股票价格和购买价格。 Then recall them to sell at a different price.然后召回他们以不同的价格出售。 The problem I am having is when I try to store my second stock, quantity, and price it deletes the first stock from the tree.我遇到的问题是,当我尝试存储我的第二个库存、数量和价格时,它会从树中删除第一个库存。 If you need more of my code, please ask but here is my Map method for storing the keys and values:如果您需要更多我的代码,请询问,但这里是我的 Map 存储键和值的方法:

    private String getPurchaseMap(String stockCode, Double quantityPurchased, Double purchasePrice) {
        Map<String, Deque<Block>> maintainStocks = new TreeMap<String, Deque<Block>>();
        var stock = new Block(stockCode, quantityPurchased, purchasePrice);
        var deque = new ArrayDeque<Block>();
        deque.offerFirst(stock);
        maintainStocks.put(stockCode, deque);
        var tempObj = maintainStocks.get(stockCode).peekFirst();
        for (var stocks : maintainStocks.entrySet()) {
            for (var test : stocks.getValue()) {
                System.out.printf("%s%n", stocks.getKey());
                System.out.println(tempObj.getQuantity());
                System.out.println(tempObj.getPrice());
            }
        }
            return null;
    }

Map.put method will replace the old value with new value for same key Map.put方法将用相同键的新值替换旧值

Associates the specified value with the specified key in this map (optional operation).将指定值与此 map 中的指定键关联(可选操作)。 If the map previously contained a mapping for the key, the old value is replaced by the specified value.如果 map 先前包含键的映射,则旧值将替换为指定值。 (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.) (当且仅当 m.containsKey(k) 将返回 true 时,才说 map m 包含密钥 k 的映射。)

So you can use compute method in Map for adding the values to ArrayDeque which are having same key.因此,您可以使用Map中的计算方法将具有相同键的值添加到ArrayDeque If key doesn't exists than add create new ArrayDeque and value to it, If key already exists then add value to existing ArrayDeque如果键不存在,则添加创建新的ArrayDeque和值,如果键已经存在,则将值添加到现有的ArrayDeque

map.compute(key, (k, v) -> (v == null) ? new ArrayDeque<Block>() : v).offerFirst(stock);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM