gpt4 book ai didi

java - 使用两个列表进行流式查询

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:52:59 26 4
gpt4 key购买 nike

我有一个 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;
}

最佳答案

你可以试试这个。你在这里得到了一些好处,containsHashSet 中比 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;
}

关于java - 使用两个列表进行流式查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38894957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com