Java - Streams from Other Sources

Introduction

The chars() method in the CharSequence interface returns an IntStream whose elements are int values.

You can use the chars() method on a String, a StringBuilder, and a StringBuffer to obtain a stream of characters.

The following code creates a stream of characters from a string, filters out all digits and whitespaces, and prints the remaining characters:

Demo

public class Main {
  public static void main(String[] args) {
    String str = "5 int and 25 floats";
    str.chars().filter(n -> !Character.isDigit((char) n) && !Character.isWhitespace((char) n))
        .forEach(n -> System.out.print((char) n));

  }/*from w  w  w. j a  v a2s .com*/
}

Result

The splitAsStream(CharSequence input) method from java.util.regex.Pattern class returns a stream of String whose elements match the pattern.

The following code obtains a stream of strings by splitting a string using a regular expression (" , ").

The matched strings are printed on the standard output.

Demo

import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    String str = "Java,Jeff,Javascript";
    Pattern.compile(",").splitAsStream(str).forEach(System.out::println);

  }//from  www  .  ja v  a 2s.c  o  m
}

Result