Reputation:
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
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:
Ps: updating key and value means deleting old key, not changing it.
Map specification:
Upvotes: 1
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
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