Notes on Java's Stream API and SQL

A note on the contrast between Java's Stream API and SQL.

Official Stream documentation

Excerpt from the official Java 8 documentation. https://docs.oracle.com/javase/jp/8/docs/api/java/util/stream/Stream.html

A sequence of elements that supports sequential and parallel aggregate operations. (Omitted) Collection and stream have similarities on the surface, but have different purposes. The collection is primarily focused on efficient management and access of elements. Streams, on the other hand, do not have a means of direct access or manipulation of elements, but instead focus on declaratively describing the source and the computational operations performed on that source. (Omitted) Stream pipelines can run either sequentially or in parallel. This run mode is one of the properties of the stream. When you create a stream, you make an initial choice of sequential or parallel execution.

It's hard to understand even if I read the document because I don't understand enough, but if I write it roughly, it's like this.

--Similar to a collection --Perform an aggregation operation --Does not directly access or manipulate elements (get, remove) --Processing can be selected sequentially or in parallel

Aggregation operations will be easier to understand if you can imagine SQL.

List of comparison between Stream API and SQL

Stream API Corresponding SQL Description
Stream#map SELECT An operation that converts an element in a Stream to another value or object
Stream#filter WHERE An operation that filters only data that matches the conditions. It is necessary to write an expression that returns boolean as an argument.
Stream#max MAX Get maximum
Stream#min MIN Get the minimum value
IntStream#sum
Collectors#summingInt
SUM Get total

Sample code

Prerequisites

--Premise that the lombok plugin is installed --The scope is appropriate

Person data and class

Define the table that stores the person data and the class that holds the data as follows.

■ Person table

id name age job
1 yamada 25 ---:
2 suzuki 28 ---:
3 sato 30 ---:
4 nakamura 41 ---:
5 yamamoto 38 ---:
6 akiyama 22 ---:
7 tanabe 43 ---:
8 ito 24 ---:

■ Person class

Persion.java


@Data
@AllArgsConstructor
public class Person {
    private int id;
    private String name;
    private int age;
}

Furthermore, a list containing all the data of the Person table is defined as List <Person>. List <Person> is synonymous with:

List<Person> personList = Arrays.asList(
    new Person(1, "yamada", 25),
    new Person(2, "suzuki", 28),
    new Person(3, "sato", 30))
    new Person(4, "nakamura", 41))
    new Person(5, "yamamoto", 38))
    new Person(6, "akiyama", 22))
    new Person(7, "tanabe", 43))
    new Person(8, "ito", 24))
);

Stream#map

Java


List<String> nameList = personList.stream()
        .map(Person::getName)
      .collect(Collectors.toList()); 

SQL


SELECT
  p.name
FROM
  Person p


Result
["yamada", "suzuki", "sato", "nakamura, "yamamoto", "akiyama", "tanabe", ito]

Stream#filter

Java


List<String> nameList = personList.stream()
        .filter(p -> p.getAge() >= 40)
        .map(Person::getName)
        .collect(Collectors.toList()); 

SQL


SELECT
  p.name
FROM
  Person p
WHERE
  p.age >= 40 


Result
["nakamura", "tanabe"]

Stream#max

Java


Integer max = personList.stream()
        .map(Person::getAge)
        .max(Comparator.comparingInt(x -> x))
        .orElse(null);

SQL


SELECT
  max(p.age) max_age
FROM
  Person p


Result
43

Stream#min

Java


Integer max = personList.stream()
        .map(Person::getAge)
        .min(Comparator.comparingInt(x -> x))
        .orElse(null);

SQL


SELECT
  min(p.age) min_age
FROM
  Person p


Result
22

IntStream#sum/Collectors#summingInt

Java


int sum = personList.stream()
        .mapToInt(Persion::getAge)
        .sum();

int sum2 = personList.stream()
        .collect(Collectors.summingInt(Persion::getAge));

SQL


SELECT
  sum(p.age) sum_age
FROM
  Person p


Result
251

Recommended Posts

Notes on Java's Stream API and SQL
Notes on Java path and Package
Let's consider the meaning of "stream" and "collect" in Java's Stream API.
Nowadays Java lambda expressions and Stream API
Stream API memo
Notes on implementing google books api in java okhttp and gson versions and okhttp and jackson versions
Summary of mutual conversion between Groovy's Default Groovy Methods and Java's Stream API
Java Stream API
Install and switch between multiple Javas on Ubuntu
[For beginners] About lambda expressions and Stream API
Upload and download notes in java on S3
Stream API basics
[In-house study session] Java basics-Lambda expression and Stream API- (2017/07/13)
Java's Stream API is super fast if used well
Notes on Protocol Buffers
[Java] Stream Collectors notes
python notes on docker
Stream API (Collectors class)
[Android] Notes on xml
[Java] Stream API / map
Stream API map method
credentials.yml.enc and master.key <Notes>
Notes on regular expressions
Java8 Stream API practice
Launch Nuxt.js + Rails API on Docker and try CRUD operation
credentials.yml.enc and master.key <Notes>
[Java] Basic types and instruction notes
Internal class and lambda study notes
Notes on Java path and Package
Notes on Java's Stream API and SQL
Rails validation and null: false Personal notes
I was addicted to using Java's Stream API in Scala