Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over Map (Specifically TreeMap) in Java starting from a key-value pair

Tags:

java

treemap

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.

like image 748
sachinr Avatar asked Oct 14 '25 08:10

sachinr


2 Answers

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
}
like image 120
Eran Avatar answered Oct 18 '25 05:10

Eran


Use tailMap,

treeMap.tailMap(fromKey)

You can also use it like this;

for (Map.Entry<String, String> entry : treeMap.tailMap("key1").entrySet()) {
   // Do something
}
like image 30
Petar Butkovic Avatar answered Oct 18 '25 04:10

Petar Butkovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!