Reputation: 9134
I wanna sort a collection of dates value pair. My key is Date and the value is a String. So I selected a TreeMap.
Now,
Is the following iterator is sorted according similar to the TreeMaps key. I tried few loops but still have a doubt
Iterator<Date> iter = policyMap.keySet().iterator();
Is there any way to get the next key without incrementing the iterator's index.
Is there any equalant way than this policyMap.higherKey(cpDate))
before java 6.
Finally I ashamed of my self that I tried for following too.
TreeMap<Date, String> policySubMap =
new TreeMap<Date, String>policyMap.tailMap(cpDate));
policySubMap.remove(policySubMap.firstKey());
System.out.println(" | amount > " + policySubMap.firstKey());
This is my complete code :
public void controller(){
TreeMap<Date, String> policyMap = new TreeMap<Date, String>();
Calendar cal = Calendar.getInstance();
policyMap.put(addDate(cal, 2).getTime(), "Amount is 10");
policyMap.put(addDate(cal, 10).getTime(), "Amount is 10");
policyMap.put(addDate(cal, -10).getTime(), "Amount is -10");
policyMap.put(addDate(cal, 11).getTime(), "Amount is 11");
policyMap.put(addDate(cal, -11).getTime(), "Amount is -11");
policyMap.put(addDate(cal, -12).getTime(), "Amount is -12");
Iterator<Date> iter = policyMap.keySet().iterator();
while (iter.hasNext()) {
Date cpDate = iter.next();
System.out.print("From "+cpDate + " to " + policyMap.get(cpDate));
// if(iter.hasNext())System.out.println(" | amount > " + policyMap.higherKey(cpDate)); // This is not supporting in before java 6
if(iter.hasNext()){
TreeMap<Date, String> policySubMap = new TreeMap<Date, String>(policyMap.tailMap(cpDate));
policySubMap.remove(policySubMap.firstKey());
System.out.println(" | amount > " + policySubMap.firstKey());
}
else System.out.println("Checking date");
}
}
public Calendar addDate(Calendar cal, int amount) {
cal.add(Calendar.DATE, amount);
return cal;
}
Upvotes: 1
Views: 256
Reputation: 533500
Yes
No. You can use a second iterator, or mroe efficiently save the previous value.
You can use
Date nextKey = treeMap.tailMap(new Date(date.getTime()+1)).firstKey();
Upvotes: 3