By: Made Susantho, Mitrais Analyst Programmer
Java already has a Collection API that has capabilities to perform operations against Collection objects. However, Collection API does not provide a higher-level API that makes data manipulation easier, so we have to write many lines of code just to perform a simple operation.
Java 8 was released with some new feature such as Stream, Collector, Optional, Lambda etc. Stream API answers the shortcomings, by creating a simple API, to the point and effectively.
Let’s look at the difference between Stream API and Collection API with the following example case.
From profiling data provided, retrieve patient data then show the profile name and sort by name.
Looking at the code above we can see that with Collection API – Java developers would have to write more than 20 lines of code just for one simple operation.
The expected result is quite simple: filter profile data, sort by name and show the results. So why so many lines of code?
How about using Stream API?
OK, let’s try to use Stream API to highlight the difference with the Collection API.
Not only fewer lines of code, the code is much more descriptive (and therefore maintainable). Java developers reviewing this code later will read and understand it much more easily and they will find the key points in the code at a glance:
- filter: selecting data with certain criteria
- sorted: sorting data with certain criteria
- map: retrieve desire data
- collect: execute Stream and change the data as List.
Above is only one simple case – but you can see now one of the benefit of using Java 8 Stream API. Java 8 is a great version for Java, with syntax changes, new methods and types and “hidden” changes that can be applied to your existing application and for developers looking to improve their productivity.
Just start (happy) coding!