简体   繁体   中英

Stream query with two lists

I have a list of Visit objects, now I want to build another list containing available hours for given day;

public class Visit {
    private int id;
    private Date date;
    private Time time;
    private Pet pet;
    private Vet vet;  

this is the array String[] containing all visit hours:

public class VisitTime {

    private static final String[] visitTime = 
        {"09:00:00","09:30:00","10:00:00","10:30:00","11:00:00","11:30:00","12:00:00",
                "12:30:00","13:00:00","13:30:00","14:00:00","14:30:00","15:00:00","15:30:00","16:00:00","16:30:00"};

so now Im getting from Db list of visits (each visit has defined time), and checking if there is any other free time to schedule a visit.

I have written two methods to do so, one with iteration second with streams, both working as expected.

What I'm asking is how can I rebuild this method to NOT use terminal method twice.

public List<String> getHoursAvailable12(int vetId, String date){
        List<Visit> visitList = getVisitByVetIdAndDate(vetId, date);
        List<String> hoursAvailable = new ArrayList<>(Arrays.asList(VisitTime.getVisittime()));


        List<String> hoursTaken = visitList.stream().map(Visit::getTime).map(Time::toString).collect(Collectors.toList());

        return hoursAvailable.stream().filter(x -> !hoursTaken.contains(x)).collect(Collectors.toList());
    }

and here is old-school method with collections:

public List<String> getHoursAvailable(int vetId, String date){
        List<Visit> visitList = getVisitByVetIdAndDate(vetId,date);
        ArrayList<String> hoursAvailable = new ArrayList<>(Arrays.asList(VisitTime.getVisittime()));

        for(Visit x : visitList){
            {
            String time = x.getTime().toString();
            if(hoursAvailable.contains(time)) hoursAvailable.remove(time);
            }
        }
        return hoursAvailable;
    }

You can try this. You get some benefit here, contains is faster in HashSet compared to List

public Set<String> getHoursAvailable(int vetId, String date){
    List<Visit> visitList = getVisitByVetIdAndDate(vetId,date);
    Set<String> hoursAvailable = new LinkedHashSet<>(
          Arrays.asList(VisitTime.getVisittime()));

    visitList.stream()
       .map(Visit::getTime)
       .map(Time::toString)
       .forEach(vt-> hoursAvailable.removeIf(s->s.equals(vt)));

    return hoursAvailable;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM