Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you prefer Java 8 Stream API instead of direct hibernate/sql queries when working with the DB

Tags:

Recently I see a lot of code in few projects using stream for filtering objects, like:

library.stream()           .map(book -> book.getAuthor())           .filter(author -> author.getAge() >= 50)           .map(Author::getSurname)           .map(String::toUpperCase)           .distinct()           .limit(15)           .collect(toList())); 

Is there any advantages of using that instead of direct HQL/SQL query to the database returning already the filtered results.

Isn't the second aproach much faster?

like image 228
strash Avatar asked Apr 09 '17 07:04

strash


People also ask

What are the advantages of stream API in Java 8?

Java 8 Stream support sequential as well as parallel processing, parallel processing can be very helpful in achieving high performance for large collections. All the Java Stream API interfaces and classes are in the java. util. stream package.

Why do we need stream API in Java?

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.

When should I use Java 8 streams?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.

Does Java 8 stream improve performance?

In Java8 Streams, performance is achieved by parallelism, laziness, and using short-circuit operations, but there is a downside as well, and we need to be very cautious while choosing Streams, as it may degrade the performance of your application.


1 Answers

If the data originally comes from a DB it is better to do the filtering in the DB rather than fetching everything and filtering locally.

First, Database management systems are good at filtering, it is part of their main job and they are therefore optimized for it. The filtering can also be sped up by using indexes.

Second, fetching and transmitting many records and to unmarshal the data into objects just to throw away a lot of them when doing local filtering is a waste of bandwidth and computing resources.

like image 109
Henry Avatar answered Oct 16 '22 12:10

Henry