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)
?
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.
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.
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.
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.
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();
}
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")
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With