I have a TreeMap, I wanted to iterate over it and print key-value pairs. But I dont want to start from the beginning, I want to start from a particular key-value pair.
Basically I want to do this -
TreeMap<String, String> treeMap = new TreeMap<String, String>();
//Populate it here
treeMap.get("key1");
//get the iterator to the treemap starting from the key1-value1 pair and iterate
I know how to do this if I want to iterate from start to end, but I dont find any answers to this.
You can do this with tailMap :
Iterator<String> iter = treeMap.tailMap("key1").keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
String value = treeMap.get(key);
// do your stuff
}
or
Iterator<Map.Entry<String,String>> iter = treeMap.tailMap("key1").entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> entry = iter.next();
// do your stuff
}
Use tailMap
,
treeMap.tailMap(fromKey)
You can also use it like this;
for (Map.Entry<String, String> entry : treeMap.tailMap("key1").entrySet()) {
// Do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With