0

I have an array list of dates spanning for several years i.e. ArrayList<Date> dateList I have an object that represents a grid of months for each year i.e.

public class DateTileGrid
{
    private int mCurrentYear;
    private ArrayList<Date> mDateTiles;
        ... // GETTERS AND SETTERS
}

I want to create an ArrayList<DateTileGrid> that will contain the relevant dates for each year.

I know how to do it with loop (nasty nested loops) but I hope there is a cleaner way to achieve that.

1
  • 1
    I think @Murali method works best for you, as you need to add a year filter to this (unless you are able to filter the dates and group them at a lower level) Commented Aug 10, 2013 at 10:24

1 Answer 1

2

Probably this is what you need until java 8 closures comes

HashMap<Integer, DateTileGrid>  dataGridMap = new HashMap<>();
for (Date date: dateList) {
    int year = date.getYear(); //Deprecated.. use something better
    DateTileGrid dataGrid = dataGridMap.get(year);
    if(dataGrid == null){
        dataGrid = new DateTileGrid();
        dataGrid.setCurrentYear(year);
        dataGrid.setDateTiles(new ArrayList<Date>());
        dataGridMap.put(year, dataGrid);
    }
    dataGrid.getDateTiles().add(date);
}
//Here is your result
ArrayList<DateTileGrid> result = new ArrayList<>(dataGridMap.values());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.