Search code examples
javac++dictionarytreemap

Equivalent of C++ map.lower_bound in Java


My question is very basic, but I couldn't find the solution myself.

I am used to writing algorithms in C++. There I very often use the std::map structure, together with all the auxiliary methods it provides.

This method returns iterator to the first element of the map with key >= to the key given as parameter. Example:

map<int, string> m;
// m = { 4 => "foo", 6 => "bar", 10 => "abracadabra" }
m.lower_bound(2); // returns iterator pointing to <4, "foo">
m.lower_bound(4); // returns iterator pointing to <4, "foo">
m.lower_bound(5); // returns iterator pointing to <6, "bar">

The cool thing is that the C++ map is based on red-black trees and so the query is logarithmic (O(log n)).

Now I need to implement a certain algorithm in Java. I need similar functionality as the one I just described. I know I can use TreeMap which is implemented in ordered tree. However I don't seem to find equivalent of the method lower_bound. Is there such?

Thank you very much for your help.


Solution

  • I guess that you're looking for TreeMap. Take a look at ceilingKey/Entry methods.