sys_debug
sys_debug

Reputation: 4003

Java Compare items in Arraylist with similar items in TreeMap

I have a TreeMap that contains all dates of a given year as keys and value for each key is 46. Now the user supply a start date and end date. I want to check capacity (i.e. value for each date i.e. 46) for start date and end date and range in between in the map. How can this be done?

I can create a an arraylist with range of date, and I thought maybe iterating over both structures(arraylist and treemap) at the same time and comparing items would work. Not sure though. What do you think?

Upvotes: 0

Views: 372

Answers (1)

MartinZ
MartinZ

Reputation: 438

A navigable map (such as a tree map) can give you a map with a range of keys through its subMap(fromKey, toKey) method.

So this should work for you:

TreeMap<Date, Integer> map = ...;
int minCapacity = Integer.MAX_VALUE; 
int maxCapacity = Integer.MIN_VALUE;
for (Integer capacity : map.subMap(fromDate, toDate).entrySet()) {
    minCapacity = Math.min(minCapacity, capacity);
    maxCapacity = Math.max(maxCapacity, capacity);
}

Upvotes: 2

Related Questions