[Java] Stream API --Stream termination processing

Stream termination

Process elements in sequence

import java.util.stream.Stream;
public class StreamForEach {
  public static void main(String[] args) {
    Stream.of("Munchkin", "Siamese", "Persian", "Tama")
    .forEach(v -> System.out.println(v));
  }
}
import java.util.stream.Stream;
public class Main {
  public static void main(String[] args) {
    Stream.of("Munchkin", "Siamese", "Persian", "Tama")
    .parallel()
    .forEach(v -> System.out.println(v));
    //Persian Tama Siamese Munchkin 
    
    /*If you want to keep the order
    .forEachOrdered(v -> System.out.println(v)); 
    Munchkin Siamese Persian Tama
    */
  }
}

Get the first value

import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {

    var str = Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
        .filter(s -> s.startsWith("S"))
        .findFirst();
      //If the orElse method is null"-"Replace with
      System.out.println(str.orElse("-")); //Siamese
  }
}
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {

    var str = Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
    .parallel()
    .filter(s -> s.startsWith("S"))
    .findAny();
     System.out.println(str.orElse("-")); //Scottish Fold
  }
}

Determine if the value meets certain conditions

//Check if all the values in the list are 0 or more
import java.util.stream.IntStream;

public class StreamMatch {

  public static void main(String[] args) {
    System.out.println(
        IntStream.of(1, 10, 5, -5, 12)
          .allMatch(v -> v >= 0)
      ); //false
  }
}

Convert to array / collection

import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    var list = Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
        .filter(s -> s.startsWith("S"))
        .toArray();
    System.out.println(list[0]); //Siamese
  }
}
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamTrans2 {

  public static void main(String[] args) {
    var list = Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
        .filter(s -> s.startsWith("S"))
        .collect(Collectors.toList());
    System.out.println(list);
  }
}
//Name the Person object array:Convert to map format of email address
public class StreamCollectMap {

  public static void main(String[] args) {
    System.out.println(
        Stream.of(
          new Person("Yamada Taro", "[email protected]"),
          new Person("Hanako Suzuki", "[email protected]"),
          new Person("Saburo Inoue", "[email protected]"),
          new Person("Kumi Sato", "[email protected]"),
          new Person("Yamada Taro", "[email protected]")
        ).collect(Collectors.toMap(
          //The argument key represents the key of the map
          Person::getName,
          //The argument value represents the key of the map
          Person::getEmail,
          //When there is a possibility of duplication
          (s, a) -> s + "/" + a
          //Overwrite value when duplicated
          // (s, a) ->  a
        ))
      );
  }
}
public class Person {
  private String name;
  private String email;
  public Person(String name, String email) {
    this.name = name;
    this.email = email;
  }
  public String getName() {
    return name;
  }
  public String getEmail() {
    return email;
  }
}

Find the maximum and minimum

import java.util.Comparator;
import java.util.stream.Stream;

public class StreamMin {

  public static void main(String[] args) {
    var str = Stream.of("Rockfish", "pacific saury", "Flounder", "Sardines", "Atka mackerel")
        .min(Comparator.naturalOrder());
      System.out.println(str.orElse("")); //Sardines
  }
}

Find the number of elements

//Find the number of strings larger than the string length 3.
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    System.out.println(
    Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
      .filter(s -> s.length() > 7)
      .count() //2
    );
  }
}

Find the total / average value

//Int array sum, average
import java.util.stream.IntStream;

public class StreamSum {

  public static void main(String[] args) {
    var list = new int[] { 5, 1, 10, -3 };
    System.out.println(IntStream.of(list).sum()); //13
    System.out.println(IntStream.of(list).average().orElse(0)); //3.25
  }
}

Combine stream values into one

With one argument:

//Combine string streams separated by commas
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {

    System.out.println(
      Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
        .sorted()
        .reduce((result, str) -> {
          return result + "," + str;
        })
        .orElse("") //Munchkin,Persian,Scottish Fold,Siamese,Tama
    );
  }
}

With 2 arguments:

import java.util.stream.Stream;
public class StreamReduce2 {
  public static void main(String[] args) {
    System.out.println(
      Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
        .sorted()
        // .parallel()
        .reduce("Himalayan", (result, str) -> {
          return result + "," + str;
        })
    ); //Himalayan,Munchkin,Persian,Scottish Fold,Siamese,Tama
  }
}

With 3 arguments:

import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    System.out.println(
      Stream.of("153", "211", "112", "350", "418", "208")
        .parallel()
        .reduce(0,
          //Get individual elements
          //The operation result is stored in result, and value receives each element.
          (result, value) -> {
            return result + Integer.parseInt(value); //Convert string value to number
          },
          //Summarize the distributed results(Parallel stream only)
          (result1, result2) -> {
            return result1 + result2; //1452
          }
      )
    );
  }
}

Collect stream elements into a collection (1)

//Sort a given string stream and convert it to a list
import java.util.ArrayList;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    System.out.println(
      Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama"
        .sorted()
        .collect(
          //Create a container that stores the value in the first value of reduction by the number of expressions
          ArrayList<String>::new,
          //Arguments are containers, individual elements
          (list, str) -> list.add(str),
          //For parallel streams
          (list1, list2) -> list1.addAll(list2)
        )
    );
  }
}

Collect stream elements into a collection (2)

import java.util.ArrayList;
//import java.util.Arrays;
import java.util.stream.Collector;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    System.out.println(
      Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
        .sorted()
        .collect(
          Collector.of(
            ArrayList::new,
            ArrayList::add,
            (list1, list2) -> {
              list1.addAll(list2);
              return list1;
            },
            Collector.Characteristics.IDENTITY_FINISH
          )
        )
    );
  }
}

Standard collector

** joining method **

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
    System.out.println(
        Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
          .sorted()
          .collect(Collectors.joining(",", "<", ">")) //<Munchkin,Persian,Scottish Fold,Siamese,Tama>
      );
  }
}

** groupingBy method **

//Categorize strings by length
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
    System.out.println(
        Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
          .sorted()
          .collect(
          //Receive element type with argument str and generate grouping key
          //Group by string
            Collectors.groupingBy(str -> str.length()
          )) //{4=[Tama], 7=[Persian, Siamese], 8=[Munchkin], 13=[Scottish Fold]}
      );
  }
}
public class Main {

  public static void main(String[] args) {
      
    System.out.println(
        Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
          .sorted()
          .collect(
            Collectors.groupingBy(
              str -> str.length(),
              Collectors.joining("/") //{4=Tama, 7=Persian/Siamese, 8=Munchkin, 13=Scottish Fold}
          ))
      );
  }
}

** partitioningBy method **

//Divide whether the character string is 7 characters or less or long
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
      
    System.out.println(
        Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
          .sorted()
          .collect(
            Collectors.partitioningBy(
              str -> str.length() > 7
          ) //{false=[Persian, Siamese, Tama], true=[Munchkin, Scottish Fold]}
        )
      );
  }
}

** collectingAndThen method **

//List streams with toList method
//Collections::Convert to read-only with unmodifiableList

import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
    System.out.println(
        Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
          .sorted()
          .collect(
            Collectors.collectingAndThen(
              Collectors.toList(),
              Collections::unmodifiableList
            )
          )
      );
  }
}

** IntSummaryStatistics class **

import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;

public class Main {

  public static void main(String[] args) {
    var summary = IntStream.of(5, 13, 7, 2, 30)
      .collect(
     //Pass a reference to the parseInt sod in the constructor, accept, combineDB
        IntSummaryStatistics::new,
        IntSummaryStatistics::accept,
        IntSummaryStatistics::combine
      );
    System.out.println(summary.getMin()); //2
    System.out.println(summary.getSum()); //57
    System.out.println(summary.getAverage()); //11.4
  }
}

Recommended Posts

[Java] Stream API --Stream termination processing
[Java] Stream API --Stream intermediate processing
Java Stream API
Java Stream termination
[Java] Stream processing
Data processing using stream API from Java 8
[Java] Stream API / map
Java Stream API cheat sheet
[Java] Introduction to Stream API
[Java] Stream API intermediate operation
Stream termination
[java8] To understand the Stream API
[Introduction to Java] About Stream API
I tried using Java8 Stream API
Basic processing flow of java Stream
Java 8 ~ Stream API ~ to start now
[JAVA] Stream type
Try using the Stream API in Java
Try Java 8 Stream
Nowadays Java lambda expressions and Stream API
Java thread processing
Try various Java Stream API methods (now)
Java string processing
Studying Java 8 (Stream)
[Java] Multi-thread processing
Stream intermediate processing
Stream API basics
Java 9 Optional :: stream
java iterative processing
[Java] How to operate List using Stream API
[Java] Stream Collectors notes
Pack API response (java)
[Java] Stream API-Stream generation
Stream API (Collectors class)
Stream API map method
Docker-Client Java API Troubleshooting
Zabbix API in Java
Java8 Stream reduction operation
JAVA constructor call processing
Java random, various processing
Java8 Stream Rough Summary
List processing to understand with pictures --java8 stream / javaslang-
[In-house study session] Java basics-Lambda expression and Stream API- (2017/07/13)
[For beginners] How to operate Stream API after Java 8
Use Java lambda expressions outside of the Stream API
Stream processing of Java 8 can be omitted so far!
About merge processing implementation including sorting function of Stream API
[Java11] Stream Summary -Advantages of Stream-
[Must-see for apprentice java engineer] How to use Stream API
Handle exceptions coolly with Java 8 lambda expressions and Stream API
[Java] Timer processing implementation method
Java Stream cannot be reused.
Measured parallel processing in Java
List processing to understand with pictures --java8 stream / javaslang --bonus
Understanding Java Concurrent Processing (Introduction)
Use Redis Stream in Java
[Java11] Stream Usage Summary -Basics-
Convert 2D array to csv format with Java 8 Stream API
Java Basic Learning Content 8 (Java API)
Java application for beginners: stream
Summary of java error processing