Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write it using streams? Java 8

I wrote a piece of code and wonder how I can write it more elegant, using streams here it is:

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

Here - some boolean is returned from a method. If specified date already exists in some task it returns false, otherwise true (so the return type answers the question raised in method's name :))

I was trying with filters on streams, but It worked just for a while, and then unit tests gave me some unexpected results so I deleted it and wrote it like Its upper. Now I want to beautify it

previously it was like this:

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

thanks in advance :)

like image 925
azalut Avatar asked Mar 21 '15 22:03

azalut


Video Answer


1 Answers

Method findFirst() return an Optional. So you can just check if optional is empty.

return !userTasklist.stream()
.filter(n -> n.getDate().equals(taskDate))
.findFirst().isPresent();

Or even easier approach.

return !userTasklist.stream().anyMatch(n -> n.getDate().equals(taskDate));

EDIT: Now unit tests should pass.

like image 87
Aleksander Mielczarek Avatar answered Sep 28 '22 12:09

Aleksander Mielczarek