[英]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.