How to get approximated values from a List in Java

145 views Asked by At

I have a list of an object which contain info for different flights and each flight has one date. What i was trying to accomplish is get the user to pick a date then I would iterate through the list to return flights on that date but also a couple of days earlier and after.

How to do it?

Logic-----------

get flights on this date, then get flights around this date

3

There are 3 answers

1
Ronny Shapiro On

You could try putting the flight objects into a map where the date is the key and the value is a list of all the flights on that date.

It would mean getting flights on a specific date is n(1) and assuming your date range is a constant (x days) you'll make additional 2x n(1) lookups.

If your bounds are infinite or potentially very large that's probably not the way to go.

0
Abhishek On

Iterate the List obtain the flight details and define a range of Date which you want to obtain

List<Flight> flights=new ArrayList<Flight>();
for(Flight f:flights)
 {
   Date d=f.getDate();
    if(d is within the desired range)
     {
        //your logic in here
     }
 }

If you want a logic from scratch what you can do is obtain the current time in millseconds and substract the milliseconds consisted in a day(i.e.. 86400000) from current time in milliseconds

 Calendar c= Calendar.getInstance();
 System.out.println(c.getTimeInMillis()-86400000);   // This will give the date one day before the current date
 Date d=new Date(c.getTimeInMillis()-86400000);
 System.out.println(d.toString());
0
Nazgul On

When you say "around this date" you need to quantify that. How many days or weeks around the date? Use that to create an upper and lower bound when extracting data from the List.