From 247bc668b1c3c6fe0607ebf3e7c31e41347e4407 Mon Sep 17 00:00:00 2001 From: Reinhard Pointner Date: Tue, 5 Apr 2016 18:06:06 +0000 Subject: [PATCH] Added Pattern/Matcher stream --- source/net/filebot/util/FileUtilities.java | 2 ++ source/net/filebot/util/StringUtilities.java | 32 +++++++++++++++++--- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/source/net/filebot/util/FileUtilities.java b/source/net/filebot/util/FileUtilities.java index 8edf551a..deb11fbf 100644 --- a/source/net/filebot/util/FileUtilities.java +++ b/source/net/filebot/util/FileUtilities.java @@ -274,6 +274,8 @@ public final class FileUtilities { } public static String getName(File file) { + if (file == null) + return null; if (file.getName().isEmpty() || UNC_PREFIX.equals(file.getParent())) return getFolderName(file); diff --git a/source/net/filebot/util/StringUtilities.java b/source/net/filebot/util/StringUtilities.java index fa13e581..dcf5b9df 100644 --- a/source/net/filebot/util/StringUtilities.java +++ b/source/net/filebot/util/StringUtilities.java @@ -1,5 +1,6 @@ package net.filebot.util; +import static java.util.stream.StreamSupport.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.stream.Collectors.*; @@ -9,7 +10,11 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; +import java.util.Spliterators.AbstractSpliterator; +import java.util.function.Consumer; +import java.util.regex.MatchResult; import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Stream; public final class StringUtilities { @@ -47,6 +52,10 @@ public final class StringUtilities { return null; } + public static Stream streamMatches(CharSequence s, Pattern pattern) { + return stream(new MatcherSpliterator(pattern.matcher(s)), false).map(MatchResult::group); + } + public static String asString(Object object) { return object == null ? null : object.toString(); } @@ -85,11 +94,24 @@ public final class StringUtilities { return values.map(StringUtilities::asNonEmptyString).filter(Objects::nonNull).collect(joining(delimiter, prefix, suffix)); } - /** - * Dummy constructor to prevent instantiation. - */ - private StringUtilities() { - throw new UnsupportedOperationException(); + public static class MatcherSpliterator extends AbstractSpliterator { + + private final Matcher m; + + public MatcherSpliterator(Matcher m) { + super(Long.MAX_VALUE, ORDERED | NONNULL | IMMUTABLE); + this.m = m; + } + + @Override + public boolean tryAdvance(Consumer f) { + if (!m.find()) { + return false; + } + f.accept(m.toMatchResult()); + return true; + } + } }