[Java] [Introduction to Java] About Stream API

4 minute read

Purpose

Those who have just started learning programming including Java language, those who have already learned, for reviewing, This time I am writing to learn about the Stream API.

[Introduction to Java]Variables and typesType conversionVariable scopeCharacter string operationOperation of arrayOperator ・Conditional branch (in preparation) ・Repeat processing (in preparation) ・About class (in preparation) ・Abstract class (in preparation) ・Interface (in preparation) ・Encapsulation (in preparation) ・About module (in preparation) ・About exception handlingAbout Lambda ・About Stream API ← now here

What is #Stream API

It is an API that can be operated on the elements of the collection by the function introduced from Java8.

Stream the collection → Intermediate operation (processing data) → End operation (get processed data)

It becomes the flow of the process.

You can write multiple intermediate operations of Stream API, so you can clearly describe the process that seems to be complicated.

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 Lambda Expression.

Stream API example

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

First of all, implement without using Stream API.

``


List<String> names = Arrays.asList("Osera", "Samura Kawauchi", "Kikuchi", "Ridge", "Nagano", "Jonouchi");
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
    }
  }
}

Next, implement a process similar to using the Stream API.

Implementation using

``

Stream API
List<String> names = Arrays.asList("Osera", "Samura Kawauchi", "Kikuchi", "Ridge", "Nagano", "Jonouchi");
names.stream()
     .filter(name -> name.length() >= 3)
     .filter(name -> name.contains("in"))
     .forEach(name -> System.out.println(name)); // Samura Kawachi Jonouchi

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

Extract only the elements that satisfy the condition with the filter method of the intermediate operation, The forEach method of the end operation outputs one element at a time.

Introduction of intermediate operations

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) // fetch only 3
       .forEach(num -> System.out.print(num + "")); // 1 2 3

3.distinct

It is a method that returns the elements without duplication.

distinct method


List<String> names = Arrays.asList("Kubo", "Endo", "Volume", "Kubo", "Okazaki", "Honda", "Volume", "Endo");
names.stream()
     .distinct() // remove duplicate elements and return
     .forEach(name -> System.out.print(name + "")); // Kubo Endo Maki 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 to 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 terminal operation

Until now, the forEach method was used as the end operation method, but I will introduce some other methods.

1.anyMatch

A method that returns a boolean depending on the condition. Returns true if at least one of the elements 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 more than 7 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. (Match all)

allMatch method


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

3.noneMatch

A method that returns a boolean depending on the condition. If even one of the elements meets the conditions, it returns false. (All non-match judgment)

``

noneMatch method
List<String> names = Arrays.asList("Suzuki", "Matsui", "Nomo", "Igawa", "Kawasaki", "Shinjo", "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

It turns out that the source code is simple and easy to read by using the Stream API, rather than writing the operation for the collection element by yourself. It may be confusing at first, but I would like to remember it firmly with the lambda expression.

Reference site

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