-1

Please any one can help how to remove particular key from hashmap and then rearrange the keys in hashmap accordingly.

Below is my code.

Set<Integer> integerSet = hashMap.keySet();
                int removekey = pos;
                ArrayList<Integer> integers = new ArrayList<>();
                for (Integer integer : integerSet) {
                    if (integer > removekey) {
                        integers.add(integer);
                    }
                }

                for (Integer integer : integers) {
                    if (hashMap.containsKey(integer)) {
                        AddCardPojo pojo = hashMap.get(integer);
                        pojo.setImagCard(cardImage[integer - 1]);
                        hashMap.remove(integer);
                        hashMap.put(integer - 1, pojo);
                    }
                }[![enter image description here][1]][1]

I have attached screenshot of error

enter image description here

Alps Rana
  • 61
  • 7

2 Answers2

0

You can directly remove a key value pair,you can directly do

 hashMap.remove(removeKey);

as for 're arranging keys in hashmap', it is a data structure which makes no guarantees of order of data. Check this answer for more

If you need a particular order as per integer, you could use arraylist

Community
  • 1
  • 1
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0

Finally it could be done. Below is my answer.

               hashMap.remove(key);

               List<AddCardPojo> hashMapsList=new ArrayList<>();

                Iterator it = hashMap.entrySet().iterator();
                while (it.hasNext()) {

                    Map.Entry pair = (Map.Entry)it.next();
                    hashMapsList.add((AddCardPojo) pair.getValue());
                }

                hashMap = new HashMap<>();
                for(int i=0; i<hashMapsList.size();i++){
                    hashMap.put(i,hashMapsList.get(i));
                }
Alps Rana
  • 61
  • 7