Ad

Update Existing Key Of HashMap

I have HashMap < Integer,String> of length 3:

1=>"Value1"
2=>"Value2"
3=>"Value3"

Now I want to decrease all keys by 1(if key>1): Output:

1=>"Value2"
2=>"Value3"

What I am trying

  for (e in hashMap.entries) {
                                val entry = e as Map.Entry<*, *>
                                var keyPos = (entry.key as Int)
                                if (keyPos != -1) {
                                    if (keyPos > 1) {
                                        keyPos = keyPos - 1
                                        if (keyPos != -1) {
                                            hashMap.put(keyPos, entry.value as String?)
                                        }
                                    }
                                }
                            }

But its not giving required output.

How to make it work without Concurrency exception.

Ad

Answer

EDIT: here is the same with Java 7 compatible code (without streams)

HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "test1");
hashMap.put(2, "test2");
hashMap.put(3, "test3");

Map<Integer, String> yourNewHashMap = new HashMap<>();
for (final Map.Entry<Integer, String> entry : hashMap.entrySet()) {
    if (entry.getKey() != 1) { // make sure index 1 is omitted
        yourNewHashMap.put(entry.getKey() - 1, entry.getValue()); // decrease the index for each key/value pair and add it to the new map
    }
}


Old answer with streams:

As a new Map Object is okay for you, I would go with the following stream: comments are inline

HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "test1");
hashMap.put(2, "test2");
hashMap.put(3, "test3");

// use this
Map<Integer, String> yourNewHashMap = hashMap.entrySet().stream()
                                       .filter(es -> es.getKey() != 1) // make sure index 1 is omitted
                                       .map(es -> new AbstractMap.SimpleEntry<Integer, String>(es.getKey() - 1, es.getValue())) // decrease the index for each key/value pair
                                       .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); // create a new map
Ad
source: stackoverflow.com
Ad