[Java] Stream API --Stream intermediate processing

Stream intermediate processing

Filter values by specified conditions

import java.util.stream.Stream;
public class Main {
  public static void main(String[] args) {
    Stream.of(
      "https://qiita.com/",
      "Neko",
      "CAT",
      "https://www.amazon.co.jp/",
      "https://ja.wikipedia.org/wiki/Neko_(%E3%82%BD%E3%83%95%E3%83%88%E3%82%A6%E3%82%A7%E3%82%A2)"
    )
      .filter(s -> s.startsWith("https://"))
      .forEach(System.out::println);
/*
https://qiita.com/
https://www.amazon.co.jp/
https://ja.wikipedia.org/wiki/Neko_(%E3%82%BD%E3%83%95%E3%83%88%E3%82%A6%E3%82%A7%E3%82%A2)
*/
  }
}

Process the given value

import java.util.stream.Stream;
public class Main {
  public static void main(String[] args) {

    Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
    .map(s -> s.length())
    .forEach(System.out::println); //8 7 7 13 4
  }
}
import java.util.stream.Stream;
public class Main {
  public static void main(String[] args) {
    Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
    .mapToInt(s -> s.length())
    .forEach(System.out::println); //8 7 7 13 4
  }
}

Process a given element

//Convert 2D array list to 1D array
import java.util.Arrays;
public class Main {
  public static void main(String[] args) {

    var list = new String[][] {
      { "neko", "nekko", "nekkko" },
      { "inu", "innu" },
      { "tori", "torri" }
    };
    //Pass a nested array with flatMap and Arrays.Stream with stream method
    //Flatten to a one-dimensional array by connecting with flatMap
    Arrays.stream(list)
      .flatMap(v -> Arrays.stream(v))
      .forEach(System.out::println);
     // neko nekko nekkko inu innu tori torri
    }
}
//Extract acronyms when flattening a two-dimensional array
import java.util.Arrays;
public class Main {
  public static void main(String[] args) {

    var list = new String[][] {
      { "neko", "nekko", "nekkko" },
      { "inu", "innu" },
      { "tori", "torri" }
    };

    Arrays.stream(list)
    .flatMap(v -> Arrays.stream(v).map(str -> str.substring(0, 1)))
    .forEach(System.out::println);
    //n n n i i t t
    }
}

Sort elements

import java.util.stream.Stream;
public class Main {
  public static void main(String[] args) {

    Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
    .sorted()
    .forEach(System.out::println);
// Munchkin
// Persian
// Scottish Fold
// Siamese
// Tama
  }
}
import java.util.stream.Stream;
import java.util.Comparator;

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

    Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
    .sorted((str1, str2) -> str1.length() - str2.length())
    .forEach(System.out::println);
    // Tama
    // Siamese
    // Persian
    // Munchkin
    // Scottish Fold

    /*Dictionary reverse order in Comparator interface
     Stream.of("Munchkin", "Siamese", "Persian", "Scottish Fold", "Tama")
     .sorted(Comparator.reverseOrder())
     .forEach(System.out::println);
    */
  }
}

Extract the m ~ nth element

//Use skip to skip 4 elements, and limit to extract 10 elements from it.
import java.util.stream.IntStream;
public class StreamLimit {
  public static void main(String[] args) {
    IntStream.range(1, 20)
      .skip(4)
      .limit(10)
      .forEach(System.out::println); //5,6,7,8,9,10,11,12,13,14
  }
}

Remove values from the beginning while satisfying the conditions

import java.util.stream.IntStream;
public class StreamDrop {
  public static void main(String[] args) {
    IntStream.of(-2, -5, 0, 3, -1, 2)
      .dropWhile(i -> i < 0)
      .forEach(System.out::println); //0,3,-1,2
  }
}

Extract only the values that satisfy the conditions from the beginning

import java.util.stream.IntStream;
public class StreamTake {
  public static void main(String[] args) {
    IntStream.of(-2, -5, 0, 3, -1, 2)
      .takeWhile(i -> i < 0)
      .forEach(System.out::println); //-2,-5
  }
}

Check the middle status of the stream

//Output stream contents before and after sorting
import java.util.stream.Stream;
public class StreamPeek {
  public static void main(String[] args) {
    Stream.of("Fish", "Grime", "echo", "Kinmokusei")
      .peek(System.out::println)
      .sorted()
      .forEach(System.out::println);
  }
}

Remove duplicate values

import java.util.stream.Stream;
public class Main {
  public static void main(String[] args) {
    Stream.of("Cat", "Cat", "Nekko", "Cat", "CatCat")
      .distinct()
      .forEach(System.out::println);
    //Cat
    //Cat
    //Nekko
    //cat Cat
  }
}
import java.util.HashSet;
import java.util.stream.Stream;

public class StreamDistinctObj {

  public static void main(String[] args) {
    var set = new HashSet<String>();
    Stream.of(
        new Person("Yamada", 40),
        new Person("Takano", 30),
        new Person("Okawa", 35),
        new Person("Yamada", 45)
      )
      //Add value to HashSet in filter method
      //HashSet.add method returns false if the value could not be added (duplicate)

      .filter(p -> set.add(p.name))
      .forEach(System.out::println);
  }
}
public class Person {
  public String name;
  public int age;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  @Override
  public String toString() {
    return String.format("%sīŧˆ%d years old)", this.name, this.age);
  }
}

Basic stream conversion

//Conversion from IntStream to DoubleStream
import java.util.stream.IntStream;
public class Main {
  public static void main(String[] args) {
    IntStream.range(1, 5)
      .asDoubleStream()
      .forEach(System.out::println);
      //1.0 2.0 3.0 4.0
  }
}

Mutual conversion between basic type and reference type streams

//From IntStream to Stream<Integer>Conversion to
import java.util.stream.IntStream;
public class Main {
  public static void main(String[] args) {
    IntStream.range(1, 5)
      .boxed()
      .forEach(System.out::println);
      //1 2 3 4
      
    IntStream.range(1, 5)
      .mapToObj(Integer::valueOf)
      .forEach(System.out::println);
      //1 2 3 4
  }
}
//Stream<Integer>Convert to IntStream
import java.util.stream.Stream;
public class StreamUnboxed {
  public static void main(String[] args) {
    Stream.of(1, 2, 3, 4)
      .mapToInt(i -> i) //Unboxing Integer → int
      .forEach(System.out::println); //1 2 3 4
    }
}

Recommended Posts

[Java] Stream API --Stream intermediate processing
[Java] Stream API intermediate operation
Java Stream API
Stream intermediate processing
[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
[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 Exercise "Intermediate"
[Java] Multi-thread processing
Java Stream termination
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!
It's not too late yet? Java Stream API all method usage example (intermediate operation)
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