[英]Create a collection of sub collection from a given Collection (Group By) in Java
I have an array list of dates spanning for several years ie ArrayList<Date> dateList
I have an object that represents a grid of months for each year ie 我有一个跨越几年的日期数组列表,即
ArrayList<Date> dateList
我有一个对象代表每年的网格数,即
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. 我想创建一个
ArrayList<DateTileGrid>
,它将包含每年的相关日期。
I know how to do it with loop (nasty nested loops) but I hope there is a cleaner way to achieve that. 我知道如何使用循环(令人讨厌的嵌套循环),但我希望有一种更清洁的方法来实现它。
Probably this is what you need until java 8 closures comes 在java 8闭包之前,这可能就是你所需要的
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.