Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best data structure for this problem?

I am using Java for this program, and I currently have a situation where I want to add key/value pairs to a table with integer keys, like

add (1, "Bobby")
add (6, "Sue")
add (3, "Mary")
add (8, "John")
add (15, "Joe")

So naturally I want to do something like a hashtable, but when I do a lookup, if it doesn't find the exact value, I would like it to return the nearest key that isn't greater than the requested key.

So for example, if I lookup 7, it should return "Sue", but if I lookup 9, it should return "John"

I'm hoping to use one of the java util classes (HashTable, TreeMap, etc) but I'm not quite sure how to do it.

like image 506
Bobby Pardridge Avatar asked Jun 12 '26 13:06

Bobby Pardridge


1 Answers

NavigableMap would do the trick.

like image 105
Eugen Constantin Dinca Avatar answered Jun 15 '26 02:06

Eugen Constantin Dinca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!