按开始和结束时间过滤带有日期的ArrayList [英] Filter an ArrayList with Dates by start and end time
问题描述
我正在实现一个简单的ListView,其中数据源是一个ArrayList,其中包含Name,Start和End日期。在iOS中,我会使用一个简单的NSPredicate来过滤数组,但在Android和Java中,我对我应该使用的内容感到困惑。欢迎任何建议。
I am implementing a simple ListView where the data source is an ArrayList with that contains Name, Start and End dates. In iOS I would use a simple NSPredicate to filter the array but here in Android and Java I am confused of what I should use. Any suggestions are welcomed.
推荐答案
您可以使用Date.before和Date.after方法。这些允许您过滤日期列表(对于特定范围(例如1月)的日期):
You can use the Date.before, and Date.after methods. These allow you to filter a list of dates (for ones in a specific range (for example January)):
a。使用带有开始日期和结束日期的Java 8过滤器。
a. Use a Java 8 filter, with a start, and end date.
b。使用Java循环/迭代器来检查开始和结束日期。
b. Use a Java loop / iterator, to check start and end date.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;
public class FilterStartAndEndDate {
private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
private Collection<Date> dateList = null;
private Date start = null;
private Date end = null;
private FilterStartAndEndDate() throws ParseException {
dateList = new ArrayList<Date>() {{
add(sdf.parse("01/01/2016"));
add(sdf.parse("02/01/2016"));
add(sdf.parse("03/02/2016"));
add(sdf.parse("04/01/2016"));
add(sdf.parse("05/01/2016"));
}};
start = sdf.parse("31/12/2015");
end = sdf.parse("01/02/2016");
}
/**
* Filter dates with Lambda
*
* @throws ParseException
*/
private void getDatesBetweenStartAndFinishWithFilter() throws ParseException {
dateList.stream()
.filter(dates -> dates.after(start) && dates.before(end))
.collect(Collectors.toList())
.forEach(januaryDate->System.out.println(januaryDate));
}
/**
* Filter dates with Iterator
*
* @throws ParseException
*/
private void getDatesBetweenStartAndFinish() throws ParseException {
Collection<Date> datesInJanuaryList = new ArrayList<>();
for (Date eachDate : dateList) {
if (eachDate.after(start) && eachDate.before(end)) {
datesInJanuaryList.add(eachDate);
}
}
for (Date eachDate : datesInJanuaryList) {
System.out.println(eachDate);
}
}
public static void main(String[] args) throws Exception {
FilterStartAndEndDate datesInJanuary = new FilterStartAndEndDate();
datesInJanuary.getDatesBetweenStartAndFinish();
datesInJanuary.getDatesBetweenStartAndFinishWithFilter();
}
}
示例代码过滤日期为1月,使用Lambda filter和Java迭代器。两者都使用方法之前和之后的日期。
The example code filter dates in January, using a Lambda filter, and a Java iterator. Both use the Date before and after methods.
这篇关于按开始和结束时间过滤带有日期的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!