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

strash :

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?

Henry :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=428547&siteId=1