Java 8 stream priority filtering

My code looks like:

for (SomeObject object : objects) {
    if (object.getSomething() == Something.somethingHighPriority) {
        return object;
    }
}

for (SomeObject object : objects) {
    if (object.getSomething() == Something.somethingLowPriority) {
        return object;
    }
}

It is used to get the first element in the collection through some condition In addition, priority is also important I need to look for an element first, and if it doesn't exist, I need to look for a second element

I want to rewrite it with the stream API, but I know that I only use stream once Now I rewrite it this way, but it seems more ugly than before

Optional<SomeObject> object = 
    objects.stream()
           .filter(object -> object.getSomething() == Something.somethingHighPriority)
           .findFirst();

if (object.isPresent()) {
    return object.get();
}

object = objects.stream()
                .filter(object -> object.getSomething() == Something.somethingLowPriority)
                .findFirst();

// No other use cases
return object.orElse(null);

Can I reduce templates?

Solution

You can link two pipes:

return objects.stream()
              .filter(object -> object.getSomething() == Something.somethingHighPriority)
              .findFirst()
              .orElseGet(() -> objects.stream()
                                      .filter(object -> object.getSomething() == Something.somethingLowPriority)
                                      .findFirst()
                                      .orElse(null));

Another method is to sort objects in descending order Getsomething () sorts the stream and returns the first element (if it has one of the two required values), but this takes a less efficient o (nlogn)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>