C ++ equivalent map.lower_bound in Java

My question is very simple, but I could not find a solution myself.

I use to write algorithms in C ++. There, I very often use the std::map structure, as well as all the helper methods that it provides.

This method returns the iterator to the first element of the map with the key> = to the key specified as a 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"> 

Most interestingly, the C ++ map is based on red-black trees, so the request is logarithmic ( O(log n) ).

Now I need to implement a specific algorithm in Java. I need the same functionality as described by me. I know that I can use TreeMap , which is implemented in an ordered tree. However, it seems I did not find the equivalent of the lower_bound method. Are there any?

Many thanks for your help.

+6
source share
4 answers

I assume you are looking for TreeMap . Take a look at streaming I / O methods.

+6
source

I hope this works for you?

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

This is a test case showing the behavior:

 @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")); } 
0
source

similar view:

In c ++

 vector lower_bound return the index 

In java

 TreeSet higher return the Key 
0
source

Source: https://habr.com/ru/post/910146/


All Articles