gpt4 book ai didi

Java - 如何过滤日期列表?

转载 作者:行者123 更新时间:2023-11-30 06:49:30 25 4
gpt4 key购买 nike

我有一个以这种形式存储日期对象的列表:

Mon Jan 30 18:00:00 GMT+00:00 2017
Mon Jan 30 21:00:00 GMT+00:00 2017
Tue Jan 31 00:00:00 GMT+00:00 2017
Tue Jan 31 03:00:00 GMT+00:00 2017
Tue Jan 31 06:00:00 GMT+00:00 2017

我需要一种方法来过滤我的列表并只保留每一天的最后一个日期。

这是我的代码的当前状态:

for(int i = 0; i< timeDate.size(); i++){

Calendar calendar = Calendar.getInstance();
calendar.setTime(timeDate.get(i));

int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int hour = calendar.get(Calendar.HOUR);

for(int j=i; j<timeDate.size(); j++){
Date currentDate = timeDate.get(j);
calendar.setTime(currentDate);

int dayC = calendar.get(Calendar.DAY_OF_MONTH);
int monthC = calendar.get(Calendar.MONTH);
int hourC = calendar.get(Calendar.HOUR);

if(day==dayC && month==monthC && hourC > hour){
timeDate.remove(i);
}
}
}

最佳答案

给你:

public static void main(String[] args){
List<String> list = new ArrayList<>();
SimpleDateFormat dateFomat = new SimpleDateFormat("E MMM dd hh:mm:ss z yyyy");
SimpleDateFormat yyyyMMddFormat = new SimpleDateFormat("yyyyMMdd");
list.add("Mon Jan 30 18:00:00 GMT+00:00 2017");
list.add("Mon Jan 30 21:00:00 GMT+00:00 2017");
list.add("Tue Jan 31 00:00:00 GMT+00:00 2017");
list.add("Tue Jan 31 03:00:00 GMT+00:00 2017");
list.add("Tue Jan 31 06:00:00 GMT+00:00 2017");

Map<String, List<Date>> dateMap = list.stream()
.map(s -> {
try {
return dateFomat.parse(s);
} catch (ParseException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.groupingBy(s -> yyyyMMddFormat.format(s), Collectors.toList()));

List<Date> lastDates = new ArrayList<>();
for(Map.Entry<String, List<Date>> entry : dateMap.entrySet()){
lastDates.add(Collections.max(entry.getValue()));
}

System.out.println(lastDates);
}

关于Java - 如何过滤日期列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42666335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com