Possible Duplicate:
Does an open-ended interval implementation exist for Java?
I'm new to Java and i would like to know what is the best data structure and how can i search through that data structure for my case: I have int intervals eg: 10-100, 200-500, 1000-5000 and for each interval i have a value 1, 2, 3, 4. I would like to know how can i save all those intervals and their values in a data structure and how can i search through that data structure to return the value for the specific interval. Eg. if i search 15, that is in interval 10-100, i would like to return 1.
Thank you
Linear Search Algorithm in Java Linear search or sequential search is the simplest search algorithm.
HashSet, LinkedHashSet and TreeSet are the implementations of Set interface which does not allow duplicate elements.
a List object can contain duplicate elements.
In computer science, an interval tree is a tree data structure to hold intervals. Specifically, it allows one to efficiently find all intervals that overlap with any given interval or point.
Use TreeMap, which is NavigableMap (Java 6 or higher).
Suppose you have entries key->value
(10->1, 100->1, 200->2, 500->2, 1000->3, 5000->3)
floorEntry(15)
will return 10->1
ceilingEntry(15)
will return 100->1
With this you can determine the interval number of 15, which is 1. You can also determine if a number is between intervals.
Edit: added example
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
map.put(10, 1);
map.put(100, 1);
map.put(200, 2);
map.put(500, 2);
map.put(1000, 3);
map.put(5000, 3);
int lookingFor = 15;
int groupBelow = map.floorEntry(lookingFor).getValue();
int groupAbove = map.ceilingEntry(lookingFor).getValue();
if (groupBelow == groupAbove) {
System.out.println("Number " + lookingFor + " is in group " + groupBelow);
} else {
System.out.println("Number " + lookingFor +
" is between groups " + groupBelow + " and " + groupAbove);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With