namalfernandolk
namalfernandolk

Reputation: 9134

Struggling among Java (Pre-6) TreeMap and Iterator index and next elements

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,

  1. 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();
    
  2. Is there any way to get the next key without incrementing the iterator's index.

  3. 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

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533500

  1. Yes

  2. No. You can use a second iterator, or mroe efficiently save the previous value.

  3. You can use

    Date nextKey = treeMap.tailMap(new Date(date.getTime()+1)).firstKey();
    

Upvotes: 3

Related Questions