I have a ContratMercan with 2 Timestamps containing start and end dates. I have to create a new entity SeguimientoSeccion for each month between this 2 dates.

I have 2 questions:

  • There is a way to improve it?
  • After this I will need to manipulate the List<SeguimientoSeccion> secciones to see which one matches other entity... I though about making a Map but there can be 2 or more sections in each month and year

private List<SeguimientoSeccion> createSectionsPerMonth(ContratMercan contrato) 
    List<SeguimientoSeccion> secciones = new ArrayList<SeguimientoSeccion>();

    Calendar start = Calendar.getInstance();
    start.set(Calendar.DAY_OF_MONTH, 1);

    Calendar end = Calendar.getInstance();
    end.set(Calendar.DAY_OF_MONTH, 2);  // for loop comparison

    for (int month = start.get(Calendar.MONTH), year = start.get(Calendar.YEAR); start.before(end); month = start.get(Calendar.MONTH), year = start.get(Calendar.YEAR)) {
        SeguimientoSeccion seccion = new SeguimientoSeccion();
        seccion.setMonth(month + 1);  // natural month number

        start.add(Calendar.MONTH, 1);


    return secciones;

1 Answer 1


The code would be simpler if you used a Calendar object as the loop variable.

Calendar current = …;
Calendar end = …;

for (; current.before(end); current.add(Calendar.MONTH, 1)) {
    SeguimientoSeccion seccion = new SeguimientoSeccion();
    seccion.setMonth(1 + current.get(Calendar.MONTH));  // natural month number

Consider implementing a SeguimientoSeccion.setMonthYear(m, y) method instead, as it's probably useless to set one of the fields without also setting the other.

  • \$\begingroup\$ Already implemented, works and looks great.:). Any idea about how to make a Collection or Map to refer the objects later? \$\endgroup\$ Nov 10, 2015 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.