0
public class Data
 {
    public static void main(String[] args) {
      Map<String, String> data = new LinkedHashMap<String, String>();
      data.put("1", "A");
      data.put("2", "B");
      data.put("3", "C");
      data.put("4", "D");
    }
 }

I want to insert a new Element at position 2 and Move other element One step Down ? is it possible

Before

  "1", "A"
  "2", "B"   
  "3", "C"   
  "4", "D"

After

  "1", "A"
  "2", "New Element"
  "3", "B"  
  "4", "C"   
  "5", "D"
  • 1
    you are suggesting that your `keys` get renamed when you insert a new element?, How would you ever find your data again? – Scary Wombat Jul 06 '16 at 05:00
  • it is not an Array. its a key-value pair relational mapping know as `HashMap` . So, You need to change each key manually as you want – Vikrant Kashyap Jul 06 '16 at 05:02
  • This would work if the key is just the node number of a linked list. Have the put function convert the key to an integer and then iterate through the linked list looking for the node. The problem is that search operations would be O(n) instead of O{log n) so you should only use it for a small range of keys. – Jerry Jeremiah Jul 06 '16 at 05:13

2 Answers2

1

You are using the wrong datastructure for your needs. I guess the key in your map is just the index and therefor unneeded. What you perhpas better should use is an ArrayList. There you can add(int index,Object o) your element as you said you need to.

Henning Luther
  • 2,067
  • 15
  • 22
0

I am not sure what you are trying to achieve here. But this code should do it.

String temp1 = "New Element";
String temp2 = "";
Set<String> keys = data.keySet();
for(String key:keys){
    if(key.compareTo("2")>=0){
        temp2 = data.get(key);
        data.put(key,temp1);
        temp1 = temp2;
    }
}
data.put(keys.size()+1,temp1);

This of the assumption the keys you will enter will be in ascending order

anand
  • 1
  • 1