1

我想对日期值对的集合进行排序。我的键是日期,值是字符串。所以我选择了一个TreeMap。

现在,

  1. 就是下面的迭代器是按照类似于TreeMaps的键排序的。我尝试了几个循环,但仍有疑问

    Iterator<Date> iter = policyMap.keySet().iterator();
    
  2. 有没有办法在不增加迭代器索引的情况下获取下一个键。

  3. 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;
}
4

1 回答 1

3
  1. 是的

  2. 不,您可以使用第二个迭代器,或者 mroe 有效地保存以前的值。

  3. 您可以使用

    Date nextKey = treeMap.tailMap(new Date(date.getTime()+1)).firstKey();
    
于 2012-06-11T12:31:49.693 回答