简体   繁体   中英

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)
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 . 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:

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.

Alternatively you could use a true Multimap from a third party library such as guava.

Summing the values would simply be:

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

Assuming that the values are List which makes the stream an IntStream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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