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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.