Timer in java

Is there a way in Java to save time ranges as a key in a Hashmap ? I have one Hashmap and I keep time slots. For instance:
I enter the range 0-50 as a key, and for this key I will store some other objects as a value. Now, when I say 10, I should get the appropriate value for this key.
Any value between 0-50 should get this object.

 Map map = new HashMap(); map.put(0-50,"some object") map.put(51-100,"some other object") 

now when i say map.get(10) it should be able to get "some object". Please suggest how to do this?

+4
source share
4 answers

Assumptions: non-overlapping ranges.

You can save the start point and end point of ranges in a TreeSet. The starting point and end point are objects that save the start and end time, respectively, plus (link to) the object. You must define a comparison function so that the objects are ordered by time.

You can get an object using the floor () or ceiling () function of the TreeSet.

Note that ranges must NOT overlap, even at endpoints (e.g. 3-6 and 6-10)

This will give you the complexity of the log for inserting and querying a range.

+2
source

I would not use a map, instead I will try with R-Tree . An R-tree is a tree structure designed to index spatial data. It stores rectangles. It is often used to check if a point (coordinate) is inside another geometry. These geometries are approximated by rectangles, and they are stored in a tree.

To save the rectangle (or information about it), you only need to save the coordinates of the lower left and upper right corners. In your case, this will be the lower and upper boundary of the time interval. You can think of it as if all y values ​​were 0. Then you can query a tree with your time value.

And of course, you save the value on each sheet (time span / rectangle)

A simple google search for r-tree java yielded some outstanding results. Implementing your own R-tree is not trivial, but it is not too difficult if you understand the principle of reinstalling the tree when inserting / deleting. In your one-dimensional case, this can become even simpler.

+4
source

You need to map ranges to a single key, why don't you use something like a rangemanager object that returns key 1 for any value between min and max, for example. alternatively, you can put some object as a value for all keys from 1 to 50 using the for loop, but that would be a waste in my eyes.

+1
source

If it is a non-overlapping and equi long range, that is, a range divided by 50, you can solve this problem by storing the hash for maximum numbers like

50 - "some object", 100 - "another object", etc.

if the input is 10, print several of 50 at once and get the value for this key.

You can get several 50 at once

  • input reception mode speaks for input 90, i.e. 90% 50 = 40
  • calculate the difference in the result of step 1 with 50. that is, 50 - 40 = 10
  • add the result of step 2 for input, i.e. 90 + 10 = 100
+1
source

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


All Articles