Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream API how to improve expression

I have the following code:

public List<Entry> getEntriesForUserId(int userId) {
    User u = DataBaseConnector
        .getAllUsers()
        .stream()
        .filter(user -> user.getUserId() == userId)
        .findFirst()
        .orElse(new User(-1, "Error");
    return u.getEntries();
}

getEntries() returns a List<Entry>.

How can I add the return statement into this lambda expression? Something like .map(User::getEntries)?

like image 514
ItFreak Avatar asked Aug 14 '18 09:08

ItFreak


People also ask

What would be a good way of describing streams in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

Why stream API lazy in Java?

Streams are lazy because intermediate operations are not evaluated unless terminal operation is invoked. Each intermediate operation creates a new stream, stores the provided operation/function and return the new stream. The pipeline accumulates these newly created streams.

Does Java stream improve performance?

The most important skill a Java developer, dabbling in performance improvements, should possess is the ability to use just enough stream pipelines to keep a code readable while using enough loops to make run times faster. While filtering out stuff from collections using streams is fun, there is no need for that.

Are Java 8 streams lazy?

The Java 8 Streams API is fully based on the 'process only on demand' strategy and hence supports laziness. In the Java 8 Streams API, the intermediate operations are lazy and their internal processing model is optimised to make it being capable of processing the large amount of data with high performance.


3 Answers

You don't need lambda to return the list, you can just say:

public List<Entry> getEntriesForUserId(int userId) {
    return DataBaseConnector
             .getAllUsers()
             .stream()
             .filter(user -> user.getUserId() == userId)
             .findFirst()
             .orElse(new User(-1, "Error")
             .getEntries();
}
like image 106
S.K. Avatar answered Sep 22 '22 21:09

S.K.


The answer is here already, but let me add one more thing - remember to use orElseGet instead of orElse in such cases. It will not create User eagerly:

.orElseGet(() -> new User(-1, "Error")
like image 35
Grzegorz Piwowarek Avatar answered Sep 20 '22 21:09

Grzegorz Piwowarek


Since the entire Stream method chain returns a single User u and then you call return u.getEntries();, feel free to append the second line to the end of Stream and return it as is:

return DataBaseConnector.getAllUsers().stream()
                                      .filter(user -> user.getUserId() == userId)
                                      .findFirst()
                                      .orElse(new User(-1, "Error"))
                                      .getEntries();
like image 42
Nikolas Charalambidis Avatar answered Sep 21 '22 21:09

Nikolas Charalambidis