Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 450
Boris Strandjev Avatar asked Mar 07 '12 09:03

Boris Strandjev


2 Answers

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

like image 83
Nikola Smiljanić Avatar answered Oct 21 '22 13:10

Nikola Smiljanić


I hope this works for you?

SortedMap tail = <Sorted Map Object>.tailMap(target);
if (!tail.isEmpty())
{
    upper = tail.firstKey();
}
like image 34
S.P. Avatar answered Oct 21 '22 13:10

S.P.