开发者

Get the last 3 values of a TreeMap

I have a Date/String TreeMap and I want to loop through the N last entries.

TreeMap<Date,String> map = new 开发者_StackOverflow中文版TreeMap<Date,String>();
map.put(new Date(2011,1,1), "32,1");
map.put(new Date(2011,3,1), "35");
map.put(new Date(2011,4,5), "38,9");
map.put(new Date(2011,8,2), "57!!");

Then I'm lost. I've found this :

NavigableSet<Date> dates = donnees.descendingKeySet();

Then I don't know how to say something like :

for(key in dates and i ; i from 0 to N)
{ do something }

Any help ?


It looks like you want to iterate though the descendingMap():

private static final int N = 3;
...
int i = 0;
for (Map.Entry entry : map.descendingMap().entrySet()) {
    if (i++ < N) {
        System.out.println(entry);
    }
}

Console:

Fri Sep 02 11:39:05 EDT 2011=57!!
Thu May 05 11:39:05 EDT 2011=38,9
Fri Apr 01 11:39:05 EDT 2011=35

Addendum: Here's an example using Calendar in the default locale:

private static Date createDate(int year, int month, int day) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);
    return calendar.getTime();
}
...
map.put(createDate(2011, 5, 3), "3-Jun-2011");


int i=0;
for(Iterator<Date> it = dates.iterator(); it.hasNext() && i<3;) {
  Date date = it.next();
  doSomething();
  i++
}

Or (equivalent):

int i=0;
Iterator<Date> it = dates.iterator();
while(i<3 && it.hasNext()) {
  Date date = it.next();
  doSomething();
  i++
}


Do you care about the state of the tree? If not, then you could do pollLastEntry(). This will remove the last entry off the tree and give it to you. Do 3 times and you're done. Or you could flatten the tree into an arrayList and just return the last 3 elements.


Sounds like you just need to loop through the items for the first three:

    int i=0;
    for(Date date: dates){

        //Do something

        if(i++ > 2){
            break;
        }
    }


  • TreeMap implements NavigableMap.
  • NavigableMap.descendingMap().
  • descending Map.entrySet().iterator() // the first 3 entries which are of course the "last 3" because it is back to front.

You could just implement Comparator and pass it to the TreeMap so the "oldest" dates are at the head of the TreeMap.


TreeMap to Array and read the array with a for loop with the condition i < 3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜