简体   繁体   English

Java Map添加键值

[英]Java Map Adding Key Values

Method : 方法 :

public void itemAmountCollection() {
    Map<String, List<Integer>> orderItemDetails = new LinkedHashMap<String, List<Integer>>();
            ArrayList<Integer> itemsAmount = new ArrayList<Integer>();
            WebElement orderItemTable = driver.findElement(By
                    .xpath("//*[@id='tblInfo']/tbody"));
            List<WebElement> noOfItems = orderItemTable.findElements(By
                    .tagName("tr"));
            for (int i = 1; i <= noOfItems.size(); i++) {
                String itemAmount = driver.findElement(
                        By.xpath("//*[@id='tblInfo']/tbody/tr[" + i
                                + "]/td[8]")).getText();
                itemsAmount.add(Integer.parseInt(itemAmount));
                orderItemDetails.put("amount", itemsAmount);
            }
        }

with above method we collected all the item amount with Map Collections and Output for the above method is (345,7905,345) 使用上述方法,我们通过“地图收集”收集了所有项目数量,上述method is (345,7905,345)输出为method is (345,7905,345)
how can we add all the values in an particular Key (amount) 我们如何才能将所有值添加到特定键(金额)中

Expected Output : 预期产量:

8595 (i.e 345+7905+345)

I don't really get what you mean, but I'm amusing that you're trying to add all values in a List . 我并没有真正理解您的意思,但是我很想您正在尝试将所有值添加到List To do this: 去做这个:

int result = 0;
for(int i : itemsAmount)
{
    result+=1;
}
System.out.println(result);//This should print 8595.

In general Map<Key,List<Value>> structures end up needing code that looks as follows: 通常, Map<Key,List<Value>>结构最终需要如下代码:

public addValue(Key key, Value value) {
    if (!map.containsKey(key)) {
        map.put(key, new ArrayList<>());
    }
    map.get(key).add(value);
}

In your case you should replace orderItemDetails.put with similar code. 在您的情况下,应使用类似的代码替换orderItemDetails.put

Alternatively you could use a true Multimap from a third party library such as guava. 或者,您可以使用第三方库(例如guava)中的真实Multimap。

Summing the values would simply be: 将这些值相加就是:

map.get(key).stream().sum();

Assuming that the values are List which makes the stream an IntStream. 假设值为List,则将流设为IntStream。

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

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