user4274413
user4274413

Reputation:

How to add value and key in treemap by a specific index

I have tried

       int index = new ArrayList<String>(treemap.values()).indexOf("something");

But i am not getting how to replace the value and key.

Any help will be great.

Upvotes: 0

Views: 1775

Answers (3)

Beri
Beri

Reputation: 11610

You cannot, TreeMap is a sorted key map type. Keys are sorted by Red-Black tree algorithm. So keys are a in sorted order.

If you are interested in order in which your elements were added use LinkedHashMap.

Your question's anwer are:

  • remove entry under you key
  • add key with new value

Ps: updating key and value means deleting old key, not changing it.

Map specification:

  • HashMap - simple key/value pairs, unsorted, can't find insert order
  • LinekdHashMap - unsorted, but keeps insert order
  • TreeMap - sorts keys, but can't find insert order

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

Not efficiently feasible:

for (Map.Entry<String, String> entry : treemap.entrySet()) {
    if (entry.getValue().equals("something")) {
        entry.setValue("entirely different");
        //treemap.remove(entry.getKey());
        break;
    }
}

Upvotes: 0

Kayaman
Kayaman

Reputation: 73548

TreeMaps don't work that way. They're not an indexed collection (unlike Lists), so what you're trying to do just won't work.

You need to remove the old one, if the key changes, and reinsert the new key-value pair.

Upvotes: 0

Related Questions