user3572461
user3572461

Reputation: 47

How to iterate a TreeMap until a specific key?

I want iterate a TreeMap until a specific key .

      for (int i = 0 ; i < specifickey  ; i++)

How can i do this ?

Upvotes: 2

Views: 1636

Answers (3)

Bal&#225;zs &#201;des
Bal&#225;zs &#201;des

Reputation: 13807

Like every other map:

Map<Integer, Object> map = ...;

for (int key : map.keySet()) {
    if(key == yourValue) {
        //value found
    }
}

Edit: Read your question again, if you only want to find out, if a key is present, then:

if(map.containsKey(key)) {
    //do something
}

Upvotes: 0

Kumar Abhinav
Kumar Abhinav

Reputation: 6675

TreeMap implements NavigableMap which can be useful to iterate over a range of keys.It is internally backed by the Map,so any changes you do to the Map is reflected vice-versa.You should use a headMap(K toKey, boolean inclusive) to get the map

NavigableMap<K,V> navigableMap = map.headMap(toKey, true);

for(Map.Entry entry : navigableMap .entrySet()){

//use the key value pair in Map.Entry
}

Upvotes: 6

janos
janos

Reputation: 124646

If you just want to iterate over the keys:

for (String key : map.keySet()) {
    if (key.equals(target)) {
        // do something
    }
}

If you also need to access the values, then it's more efficient to iterate over the entries instead of the keys:

Map<String, Integer> map = new TreeMap<>();
String target = "something";

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    if (entry.getKey().equals(target)) {
        // do something with entry.getValue()
    }
}

Upvotes: 0

Related Questions