我写了一段代码,并想知道如何使用流来更优雅地编写代码 这是:
public boolean possibleToAddTask(LocalDate taskDate, final String username) {
List<Task> userTasklist = find(username).getTaskList();
for(Task task : userTasklist) {
if(task.getDate().equals(taskDate)){
return false;
}
}
return true;
}
这里 - 从方法返回一些布尔值。如果某个任务中已存在指定日期,则返回 false ,否则 true (因此返回类型将回答方法名称中引发的问题:))
我正在尝试使用流上的过滤器,但它只运行了一段时间,然后单元测试给了我一些意想不到的结果,所以我将其删除并将其写成它的上层。现在我想美化它
以前是这样的:
public boolean possibleToAddTask(LocalDate taskDate, final String username) {
List<Task> userTasklist = find(username).getTaskList();
try {
userTasklist.stream().filter(n -> n.getDate().equals(taskDate)).findFirst().get();
return true;
} catch (NoSuchElementException e) {
return false;
}
}
提前感谢:)
答案 0 :(得分:10)
方法findFirst()返回一个Optional。因此,您只需检查可选项是否为空。
return !userTasklist.stream()
.filter(n -> n.getDate().equals(taskDate))
.findFirst().isPresent();
甚至更容易接近。
return !userTasklist.stream().anyMatch(n -> n.getDate().equals(taskDate));
编辑:现在单元测试应该通过。
答案 1 :(得分:0)
如何做一些喜欢将List转换为Set然后调用contains():
return userTasklist.stream().map(Task::getDate).collect(Collectors.toSet()).contains(taskDate);