Equivalent of C++ map.lower_bound in Java

2019-06-17 02:41发布

问题:

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.

回答1:

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



回答2:

I hope this works for you?

SortedMap tail = <Sorted Map Object>.tailMap(target);
if (!tail.isEmpty())
{
    upper = tail.firstKey();
}


回答3:

This is a test case that shows behaviour:

@Test
public void testPrefixMatch() {

    treeMap.put("1.2.3", "bar");
    treeMap.put("1.2.3.4", "bar");
    treeMap.put("1.2.3.5.6", "bar");


    assertEquals("1.2.3.5.6", treeMap.ceilingKey("1.2.3.4.5.6.7"));
    assertEquals("1.2.3.4", treeMap.floorKey("1.2.3.4.8.6"));
    assertEquals("1.2.3.5.6", treeMap.ceilingKey("1.2.3.4.8.6"));
}


回答4:

kind of similar:

In C++

vector   lower_bound  return the index

In Java

TreeSet  higher       return the Key