nik
nik

Reputation: 19

Is there a way to Dynamically populate values into hashmap

Im trying to populate values dynamically into a hashmap and it is taking only the last values that im keeping into the map

for (int i = 0; i < 22; i++) {
    for (int j = 0; j < col.length; j++) {
        String[] Temp = finval.get(i);

        ls[i] = JasperRepo.getMapObject();
        ls[i].put(columnsList[j], Temp[j]);
    }

    m.add(ls[i]);
}

Is there any way to add values dynamically?

Upvotes: 1

Views: 349

Answers (2)

WJS
WJS

Reputation: 40034

Here is a simple demonstration. You can make this even more concise by using some advanced features of map, but the idea is the same. It separates even and odd values.


        Map<String, List<Integer>> map = new HashMap<>();
        String key;
        for (int i = 0; i < 10; i++) {
            // assign key based on value
            if (i % 2 == 0) {
                key = "evens";
            } else {
                key = "odds";
            }

           // retrieve or create the list for the items.
            List<Integer> list = map.get(key);
            if (list == null) {
                list = new ArrayList<>();
                map.put(key, list);
            }
            // add the item to the list
            list.add(i);
        }
        map.forEach((k,v)-> System.out.println(k + " -> " + v));

It prints the following:

odds -> [1, 3, 5, 7, 9]
evens -> [0, 2, 4, 6, 8]

Upvotes: 1

Petar Bivolarski
Petar Bivolarski

Reputation: 1757

Do you wish to update the values of ls[i], so that they are being incremented if there are duplicate keys?

If yes, you could try this:

    if (!ls[i].containsKey(columnsList[j])) {
        ls[i].put(columnsList[j], Temp[j]);
    } else {
        ls[i].put(columnsList[j], ls[i].get(columnsList[j]) + Temp[j]);
    }

Upvotes: 0

Related Questions