Pattern SplitAsStream And AsPredicate
Tokenize heterogeneous input lazily with splitAsStream and filter collections with Pattern.asPredicate instead of splitting whole strings into arrays.
Code
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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.