使用两个列表进行流查询

时间:2016-08-11 11:20:31

标签: java java-stream

我有一个Visit对象列表,现在我想构建另一个列表,其中包含给定日期的可用小时数;

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

这是包含所有访问时间的数组String []:

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"};

所以现在我从Db访问列表中获取(每次访问都定义了时间),并检查是否还有其他空闲时间来安排访问。

我已经编写了两种方法,其中一种方法是迭代,第二种是使用流,两种方法都按预期工作。

我要问的是如何重建此方法以不使用终端方法两次。

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

这里是收藏的老派方法:

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

1 个答案:

答案 0 :(得分:1)

你可以试试这个。您可以在此获得一些好处,与{List

相比,contains的{​​{1}}速度更快
HashSet