Iterate over Map (specifically TreeMap) in Java starting with key-value pair

I have a TreeMap, I wanted to iterate over it and print out key-value pairs. But I don't want to start from the very beginning, I want to start with a specific 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 finish, but I don't find any answers to this.

+3


source to share


2 answers


You can do it 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
}

      

+5


source


Use tailMap

,

treeMap.tailMap(fromKey)

      



You can also use it like this:

for (Map.Entry<String, String> entry : treeMap.tailMap("key1").entrySet()) {
   // Do something
}

      

+3


source







All Articles