Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an ArrayList with Dates by start and end time

Tags:

java

android

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.

like image 430
EmilDo Avatar asked Sep 27 '14 14:09

EmilDo


1 Answers

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. Use a Java 8 filter, with a start, and end date.

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();
    }
}

The example code filter dates in January, using a Lambda filter, and a Java iterator. Both use the Date before and after methods.

like image 131
chocksaway Avatar answered Oct 16 '22 03:10

chocksaway