[Introduction to Java] About Stream API

Purpose

For those who have just started learning programming including the Java language, and those who have already learned it, for review This time I'm writing to learn about ** Stream API **.

[Introduction to Java Table of Contents] -Variables and typesType conversion -Variable Scope -String operation -Array operationOperator ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation) -Exception handlingAbout lambda expression ・ About Stream API ← Now here

What is Stream API?

A function introduced from Java8, it is an API that allows you to operate on the elements of the collection.

Streaming collection → Intermediate operation (processing data) → Termination operation (obtaining processed data)

It will be the flow of processing.

Since multiple intermediate operations of Stream API can be described, even processes that look complicated can be described neatly.

In some cases, a functional interface is received as an argument of each method, and a lambda expression is used there, but the explanation there is omitted. Please see ** About lambda expression **.

Stream API example

Let's compare with a simple example how to actually handle it.

First, implement without using Stream API.

python


List<String> names = Arrays.asList("Ohsera", "Samura Kawachi", "Kikuchi", "Ridge", "Nagano", "Joey Wheeler");
for (int i = 0; i < names.size(); i++) {
  if (names.get(i).length() >= 3) {
    if (names.get(i).contains("Inside")) {
      System.out.println(names.get(i)); //Samura Kawachi Jonouchi
    }
  }
}

Then use the `Stream API to implement a similar process.

Implementation using Stream API


List<String> names = Arrays.asList("Ohsera", "Samura Kawachi", "Kikuchi", "Ridge", "Nagano", "Joey Wheeler");
names.stream()
     .filter(name -> name.length() >= 3)
     .filter(name -> name.contains("Inside"))
     .forEach(name -> System.out.println(name)); //Samura Kawachi Jonouchi

The nesting is not deep and it is easy to read, and it is simple to implement.

Extract only the elements that satisfy the conditions with the filter method of the intermediate operation, The elements are output one by one with the forEach method of the termination operation.

Introduction of intermediate operation

Earlier I introduced filter as an intermediate operation method, but I will also introduce some other methods.

1.map

It is a method that performs the processing specified for each element.

map method


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
       .map(num -> num * 2) //Double each element
       .forEach(num -> System.out.print(num + " ")); // 2 4 6 8 10

2.limit

This method returns only the specified number of elements (maxSize).

limit method


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
       .limit(3) //Take out only 3
       .forEach(num -> System.out.print(num + " ")); // 1 2 3 

3.distinct

It is a method that returns the element without duplication.

distinct method


List<String> names = Arrays.asList("Kubo", "Endo", "roll", "Kubo", "Okazaki", "Honda", "roll", "Endo");
names.stream()
     .distinct() //Duplicate elements are removed and returned
     .forEach(name -> System.out.print(name + " ")); //Kubo Endo Vol. Okazaki Honda

4.sorted

A method that sorts the elements.

sorted method


List<Integer> numbers = Arrays.asList(1, 5, 3, 2, 4);
numbers.stream()
       .sorted() //Sort in ascending order
       .forEach(num -> System.out.print(num + " ")); // 1 2 3 4 5

You can also sort in descending order by passing the reverseOrder method of the Comparator interface as the argument of the sorted method.

sorted method


List<Integer> numbers = Arrays.asList(1, 5, 3, 2, 4);
numbers.stream()
       .sorted(Comparator.reverseOrder()) //Sort in descending order
       .forEach(num -> System.out.print(num + " ")); // 5 4 3 2 1

Introduction of termination operation

Until now, the forEach method was used as the termination operation method, but we will introduce some other methods as well.

1.anyMatch

A method that returns a boolean depending on the condition. Returns true if any of the elements have a value that matches the condition. (Partial match judgment)

anyMatch method


List<String> fruits = Arrays.asList("banana", "apple", "orange", "pineapple");
boolean result = fruits.stream()
                       .anyMatch(fruit -> fruit.length() >= 7); //Determine if there is an element with 7 or more characters
System.out.println(result); // true

2.allMatch

A method that returns a boolean depending on the condition. Returns true if all the elements meet the conditions. (All match match)

allMatch method


List<Integer> numbers = Arrays.asList(2, 4, 6, 7, 8, 10);
boolean result = numbers.stream()
                        .allMatch(num -> num % 2 == 0); //Determining if all elements are even
System.out.println(result); // false

3.noneMatch

A method that returns a boolean depending on the condition. Returns false if any of the elements match the condition. (All non-match judgment)

noneMatch method


List<String> names = Arrays.asList("Suzuki", "Matsui", "Nomo", "Igawa", "Kawasaki", "Shinjo", "Yu Darvish");
boolean result = names.stream()
                      .noneMatch(name -> name.length() > 4); //Determine if there is an element with 4 or more characters
System.out.println(result); // false

At the end

I found that the source code is simpler and easier to read by using the Stream API, rather than writing the operations on the collection elements by myself. It may be confusing at first, but I want to remember it with the lambda expression.

Reference site

** Stream Oracle Official ** ** [Java] Knowledge gained by continuing to write Stream API **

Recommended Posts

[Introduction to Java] About Stream API
[Java] Introduction to Stream API
[Introduction to Java] About lambda expressions
Java Stream API
[Java] Introduction to Java
Introduction to java
Java 8 ~ Stream API ~ to start now
Articles to learn more about Stream API
[Java] Stream API / map
Java8 Stream API practice
Introduction to java command
[Introduction to Java] About type conversion (cast, promotion)
[Java] How to operate List using Stream API
Java Stream API cheat sheet
Java Stream API in 5 minutes
[Java] Introduction to lambda expressions
[Java] Stream API --Stream termination processing
Introduction to EHRbase 2-REST API
[Java] Stream API --Stream intermediate processing
[Java] Stream API intermediate operation
[Introduction to rock-paper-scissors games] Java
[For beginners] How to operate Stream API after Java 8
[Must-see for apprentice java engineer] How to use Stream API
About Lambda, Stream, LocalDate of Java8
Introduction to Functional Programming (Java, Javascript)
Initial introduction to Mac (Java engineer)
I tried using Java8 Stream API
[Java] Introduction
Convert 2D array to csv format with Java 8 Stream API
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
Data processing using stream API from Java 8
Introduction to java for the first time # 2
Try using the Stream API in Java
Nowadays Java lambda expressions and Stream API
About the procedure for java to work
Introduction to algorithms with java --Search (depth-first search)
[Introduction to Java] How to write a Java program
Try various Java Stream API methods (now)
Java 8 to start now ~ Date time API ~
Anonymous class (aiming to introduce stream api)
I tried to summarize the Stream API
Output of the book "Introduction to Java"
Introduction to monitoring from Java Touching Prometheus
[Introduction to Java] Variable declarations and types
Introduction to Java Web Apps Performance Troubleshooting
Introduction to algorithms with java --Search (breadth-first search)
Introduction to Ruby 2
About Java interface
Stream API memo
[Java] About Java 12 features
[JAVA] Stream type
[Java] About arrays
Try Java 8 Stream
Introduction to SWING
About MacinCloud introduction
Chew about API
Something about java
Where about java
About Java features
Introduction to web3j
About Java threads