简体   繁体   中英

How to loop through months using Joda-Time?

Before I mostly had to loop between days in a certain period and I used loops like this:

for(LocalDate iDate = gv.firstDate; iDate.isBefore(gv.lastDate); iDate = iDate.plusDays(1)) {
   ...
}

Now I have a TreeMap like this:

TreeMap<LocalDate, ArrayList<Email>> dates;

I want to loop over all months from gv.firstDate to gv.lastDate and get all Email s that are within that month.

Does anyone know of a good way to do this using Joda-Time?

edit:

Having it combined with this will be great, so now get from emails from the dates TreeMap.

    for(int y = 2004; y < 2011; y++) {
        for(int m = 0; m < 12; m++) {
            // get all of that month
        }
    }

You can do something similar to this:

for (Map.Entry<LocalDate, ArrayList<Email>> entry : dates) {
    if (entry.getKey().isBefore(gv.firstDate())) {
        continue;
    }

    if (entry.getKey().isAfter(gv.lastDate())) {
        break;
    }

    // process the emails
    processEmails(entry.getValue());
}

If you have the freedom to use Google Guava, you can do something like this:

Map<LocalDate, ArrayList<Email>> filteredDates = Maps.filterKeys(dates, new Predicate<LocalDate>() {
    public boolean apply(LocalDate key) {
        if (entry.getKey().isBefore(gv.firstDate())) {
            return false;
        }

        if (entry.getKey().isAfter(gv.lastDate())) {
            return false;
        }

        return true;
    }
});

// process the emails
processEmails(filteredDates);

As you are using a TreeMap you could use method http://docs.oracle.com/javase/6/docs/api/java/util/NavigableMap.html#subMap%28K,%20boolean,%20K,%20boolean%29

NavigableMap<K,V> subMap(K fromKey,
                         boolean fromInclusive,
                         K toKey,
                         boolean toInclusive)

Returns a view of the portion of this map whose keys range from fromKey to toKey.

If the keys defining the interval are not guaranteed to be in the map you can get a map containing only the values you want by doing

for(List<Email> emails : dates.tailMap(gv.firstDate).headMap(gv.lastDate).values()) {
   for(Email email : emails) {
      // do something
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM