我想对日期值对的集合进行排序。我的键是日期,值是字符串。所以我选择了一个TreeMap。
现在,
就是下面的迭代器是按照类似于TreeMaps的键排序的。我尝试了几个循环,但仍有疑问
Iterator<Date> iter = policyMap.keySet().iterator();
有没有办法在不增加迭代器索引的情况下获取下一个键。
在
policyMap.higherKey(cpDate))
java 6.
最后,我为自己也尝试追随而感到羞耻。
TreeMap<Date, String> policySubMap =
new TreeMap<Date, String>policyMap.tailMap(cpDate));
policySubMap.remove(policySubMap.firstKey());
System.out.println(" | amount > " + policySubMap.firstKey());
这是我的完整代码:
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;
}