HashMap <string,arraylist <integer =“”>&gt;得到价值

时间:2016-02-05 05:41:53

标签: android hashmap

我正在制作洗衣店应用程序。用户选择这样的项目。

enter image description here

我有三个TabBar(干洗,洗涤,洗涤和熨烫)。 我将用户选择的商品商店存储在三个不同的HashMap<String, ArrayList<Integer>>

我的值存储在这样的hashmap中。

Key:Name, Value:[Quantity, Default-Price, Qty-Total, position]
    Key: Trouser, Value: [2, 8, 16, 3]
    Key: Shirt, Value: [3, 15, 45, 0]
    Key: Coat, Value: [2, 7, 14, 2]
    Key: Pants, Value: [3, 10, 30, 1]

我想在三个不同的HashMap中加入所有第三个元素(16,45,14,30)。 总计所有项目。

5 个答案:

答案 0 :(得分:3)

在此处查找完整代码。

Java class naming conventions

答案 1 :(得分:2)

如果map是你的HashMap<String, ArrayList<Integer>>,那么迭代地图并从ArrayList获取第三个值并求它。试试这个,

    HashMap<String, ArrayList<Integer>> map = new HashMap<>();
    int sum = 0;
    for (Map.Entry<String, ArrayList<Integer>> item : map.entrySet()) {
        sum += item.getValue().get(2);
    }

答案 2 :(得分:0)

Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
        // create list one and store values
        List<Integer> valSetOne = new ArrayList<Integer>();
        valSetOne.add(5);
        valSetOne.add(8);
        // create list two and store values
        List<Integer> valSetTwo = new ArrayList<Integer>();
        valSetTwo.add(11;
        valSetTwo.add(15);
        // create list three and store values
        List<Integer> valSetThree = new ArrayList<Integer>();
        valSetThree.add(6);
        valSetThree.add(55);
        // put values into map
        map.put(1, valSetOne);
        map.put(2, valSetTwo);
        map.put(3, valSetThree);
        // iterate and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");
        for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
            Integer key = entry.getKey();
            List<Integer> values = entry.getValue();
            System.out.println("Key = " + key);
            System.out.println("Values = " + values + "n");
        }

答案 3 :(得分:0)

总结数组的第三个索引然后将其存储在变量中是多么困难。

假设这是你的hashMap

HashMap<String, ArrayList<Integer>> clothes = new HashMap<>(String,ArrayList<Integer>);

带有这些值..

Key: Trouser, Value: [2, 8, 16, 3]
Key: Shirt, Value: [3, 15, 45, 0]
Key: Coat, Value: [2, 7, 14, 2]
Key: Pants, Value: [3, 10, 30, 1]

int grandTol = 0;
for (Map.Entry<String, List<Integer>> cloth : clothes.entrySet()) {
    grandTol += entry.getValue().get(2);

}

只需循环遍历hashMap并添加值。

答案 4 :(得分:0)

试试这个。

    int sum = map.values().stream().mapToInt(v -> v.get(2)).sum();
相关问题