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.
I guess that you're looking for TreeMap. Take a look at ceilingKey/Entry methods.
I hope this works for you?
SortedMap tail = <Sorted Map Object>.tailMap(target);
if (!tail.isEmpty())
{
upper = tail.firstKey();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With