Connorelsea
Connorelsea

Reputation: 2438

How to access elements of a stream in Java 8, or return one element of a stream?

I have the method:

public Monitor getCurrentMonitor() {
    findCurrentMonitor();
    return monitors.stream().filter(a -> a.isCurrent());
}

It's purpose is to find the current Monitor (there is only one in the list), and return it. How would I accomplish this functionally, or would it be better to do it procedurally?

Upvotes: 1

Views: 3363

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

You can call findFirst(), which will return an Optional<Monitor>, then you just return the value in this Optional instance or you throw an exception if it's empty (as you said there is a current monitor in the list):

public Monitor getCurrentMonitor() {
    return monitors.stream()
                   .filter(a -> a.isCurrent())
                   .findFirst()
                   .orElseThrow(() -> new NoCurrentMonitorException());
}

The orElseThrow part is to prevent calling get on an empty Optional (it might be better to throw your custom exception in this case to make the intent clear that there is no current monitor instance in the list).


I'm not sure what your findCurrentMonitor(); is doing. I guess you should just remove it as the filtering on the stream is basically what it does; i.e finding the current monitor. From a pure functionnal aspect you shouldn't call this function (findCurrentMonitor();) as it have side effects.

Upvotes: 2

Related Questions