If it seems to you that you want to use TreeMap , where the key is at the bottom of the range and the value is Range .
Then, to determine the correct range, simply use the floorEntry() method to very quickly get the closest (smaller or equal) Range that the key should contain, for example:
TreeMap<Integer, Range> map = new TreeMap<>(); map.put(1, new Range(1, 10)); map.put(11, new Range(11, 30)); map.put(31, new Range(31, 100)); // int key = 0; // null // int key = 1; // Range [start=1, end=10] // int key = 11; // Range [start=11, end=30] // int key = 21; // Range [start=11, end=30] // int key = 31; // Range [start=31, end=100] // int key = 41; // Range [start=31, end=100] int key = 101; // Range [start=31, end=100] // etc. Range r = null; Map.Entry<Integer, Range> m = map.floorEntry(key); if (m != null) { r = m.getValue(); } System.out.println(r);
Since the tree is always sorted in the natural order of the lower range border, all your searches will in the worst case be O (log (n)).
You need to add a health check when your key is completely out of bounds (for example, when the key is outside the map, it returns the last Range on the map), but this should give you an idea of how to proceed.
source share