Pattern SplitAsStream And AsPredicate

Tokenize heterogeneous input lazily with splitAsStream and filter collections with Pattern.asPredicate instead of splitting whole strings into arrays.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.regex.Pattern;

public class PatternStreams {

    // 分隔符不止一种:逗号、分号、竖线、空白都算一个分隔
    static final Pattern SEPARATOR = Pattern.compile("[,;|\\s]+");

    public static void main(String[] args) {
        String mixed = "spark, shuffle;reduce | merge, spark";

        // splitAsStream:惰性逐个产出 token,大文本不必先切成大数组
        long distinct = SEPARATOR.splitAsStream(mixed).distinct().count();
        System.out.println("distinct tokens: " + distinct);

        List<String> firstTwo = SEPARATOR.splitAsStream(mixed)
                .limit(2)
                .toList();
        System.out.println("first two: " + firstTwo);

        // asPredicate:把 Pattern 变成 String 谓词,直接过滤集合
        Pattern hex = Pattern.compile("0x[0-9a-f]+");
        List<String> tokens = List.of("0xff", "0xnope", "0x1a", "nothex");
        System.out.println("hex tokens: " + tokens.stream().filter(hex.asPredicate()).toList());
    }
}

How it works

Pattern SplitAsStream And AsPredicate comes down to the class PatternStreams and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Using it

Running the file prints labeled results such as distinct tokens:, first two:, hex tokens: — each operation’s effect is visible in the output.

Key statements

long distinct = SEPARATOR.splitAsStream(mixed).distinct().count();
List<String> tokens = List.of("0xff", "0xnope", "0x1a", "nothex");
static final Pattern SEPARATOR = Pattern.compile("[,;|\\s]+");

Interactive Tools for This Topic

FAQ

What does Pattern SplitAsStream And AsPredicate print when run?
No setup needed: run the file and look for labeled lines like `distinct tokens:`, `first two:`, `hex tokens:` in the output.