java - Obtain key of a hashmap with a range of numbers as value -
i have hashmap<integer, float>
entries:
1 -> 0.127 2 -> 0.167 3 -> 0.207 4 -> 0.247 5 -> 0.237 6 -> 0.327 7 -> 0.367 8 -> 0.407 9 -> 0.447 10 -> 0.487 11 -> 0.527 12 -> 0.567 13 -> 0.607 14 -> 0.647 15 -> 0.652
let suppose want key float 0.465 (which not existing value). 0.465
between 0.447
, 0.487
, key 10
.
the first thought came in mind achive 15 if/else if statements or switch statement. in view, wouldn't elegant , practical.
is there other way this?
a map not appropriate data structure. use treeset
instead:
treeset<float> numbers = new treeset<>(); // populate set numbers, in order, int index = numbers.headset(n).size() + 1;
this perform well: treeset finds insertion point in o(log n) time (like binary search) , list returned view (a new list not created), whole operation lightweight.
also note elements don't need added in particular order - treeset internally maintains order searching fast.
here's test code:
treeset<float> numbers = new treeset<>(arrays.aslist( 0.607f, 0.647f, 0.127f, 0.167f, 0.207f, 0.247f, 0.237f, 0.327f, 0.367f, 0.407f, 0.447f, 0.487f, 0.527f, 0.567f, 0.652f));
output:
10
Comments
Post a Comment