[英]Convert List<Date> to Map<Month, List<Date>>
我想將日期列表轉換為月份為關鍵字的地圖,值為給定月份的日期列表。
我有以下月份對象,基本上持有一個月和一年int,所以每個月都是唯一的。
public class Month implements Serializable, Comparable<Month> {
protected int year;
protected int month;
public Month(Date dag) {
Calendar cal = Calendar.getInstance();
cal.setTime(dag);
this.month = cal.get(Calendar.MONTH)+1; //zerobased to onebased
this.year = cal.get(Calendar.YEAR);
}
}
現在給出一個日期列表,我嘗試做這樣的事情:
public void addLedigeDage(List<Date> newLedigeDage) {
List<Date> datesPerMonth = new ArrayList<>();
Calendar cal = Calendar.getInstance();
for (Date date : newLedigeDage) {
cal.setTime(date);
Month month = new Month(date);
datesPerMonth = findAllDatesForGivenMonth(newLedigeDage, cal.get(Calendar.MONTH));
ledigeDageMap.put(month, datesPerMonth);
}
}
private List<Date> findAllDatesForGivenMonth(List<Date> newLedigeDage, int month) {
Calendar cal = Calendar.getInstance();
List<Date> datesForGivenMonth = new ArrayList<>();
for (Date date : newLedigeDage) {
if (cal.get(Calendar.MONTH) == month ) {
datesForGivenMonth.add(date);
}
}
return datesForGivenMonth;
}
但是代碼不干凈而且不是最優的,因為我在同一日期迭代次數太多次。
我正在使用java 1.7並且可以使用Guava。 在這種情況下我不能使用Multimap,因為我的應用程序中存在一些架構問題。
有關如何優化並使其清潔的任何建議?
有一個優雅的Java-8解決方案:
List<Date> dates = Arrays.asList(new Date(10000), new Date(100000));
Map<Month, List<Date>> byMonth = dates.stream()
.collect(Collectors.groupingBy(d -> new Month(d)));
我想我會做的事情如下:
public void addLedigeDage(List<Date> newLedigeDage) {
for (Date date : newLedigeDage) {
Month month = new Month(date);
if (!ledigeDageMap.containsKey(month)) {
ledigeDageMap.put(month, new ArrayList<>());
}
ledigeDageMap.get(month).add(date);
}
}
如果你願意,你可以提取:
if (!ledigeDageMap.containsKey(month)) {
ledigeDageMap.put(month, new ArrayList<>());
}
ledigeDageMap.get(month).add(date);
作為一個單獨的方法,稱為addDateToMap
東西要有點清潔。
您的代碼有幾個問題:第一:不要在您的代碼中(月份包含月份和年份)。 應該是一些更具體的名稱。
2nd:override equals和hashcode方法其他明智的兩個月對象具有相同的月份和年份值將被Map處理不同。
除了這個DaveyDaveDave的答案還不錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.