String.join(" > ", Arrays.asList("foo", "bar"));
从Java 8开始,我们可以使用StringJoiner
(而不是最初使用的StringBulder
)并简化我们的代码.
另外,为了避免在每次matches(" *")
调用中重新编译" *"
regex,我们可以创建单独的Pattern,它将其编译版本保存在某个字段中,并在需要时使用它.
Since Java 8 we can use StringJoiner
(instead of originally used StringBulder
) and simplify our code.
Also to avoid recompiling " *"
regex in each call of matches(" *")
we can create separate Pattern which will hold its compiled version in some field and use it when needed.
private static final Pattern SPACES_OR_EMPTY = Pattern.compile(" *");
public static String implode(String separator, String... data) {
StringJoiner sb = new StringJoiner(separator);
for (String token : data) {
if (!SPACES_OR_EMPTY.matcher(token).matches()) {
sb.add(token);
}
}
return sb.toString();
}
使用流,我们的代码可以看起来像
With streams our code can look like.
private static final Predicate<String> IS_NOT_SPACES_ONLY =
Pattern.compile("^\\s*$").asPredicate().negate();
public static String implode(String delimiter, String... data) {
return Arrays.stream(data)
.filter(IS_NOT_SPACES_ONLY)
.collect(Collectors.joining(delimiter));
}
如果使用流,则可以filter
个元素,其中Predicate
个元素.在这种情况下,我们希望谓词接受不仅是空格的字符串-换句话说,字符串必须包含非空格字符.
If we use streams we can filter
elements which Predicate
. In this case we want predicate to accept strings which are not only spaces - in other words string must contain non-whitespace character.
我们可以从Pattern中创建这样的谓词.以这种方式创建的谓词将接受任何包含子字符串的字符串,这些子字符串可以包含正则表达式可以匹配的子字符串(因此,如果正则表达式将查找"\\S"
,则谓词将接受诸如"foo "
," foo bar "
,"whatever"
之类的字符串,但不接受" "
或" "
).
We can create such Predicate from Pattern. Predicate created this way will accept any strings which will contain substring which could be matched by regex (so if regex will look for "\\S"
predicate will accept strings like "foo "
, " foo bar "
, "whatever"
, but will not accept " "
nor " "
).
所以我们可以使用
Pattern.compile("\\S").asPredicate();
或者更具描述性的否定字符串,它们只能是空格或为空
or possibly little more descriptive, negation of strings which are only spaces, or empty
Pattern.compile("^\\s*$").asPredicate().negate();
接下来,当filter将删除所有空的或仅包含空格的字符串时,我们可以collect
其余元素.感谢Collectors.joining
,我们可以决定使用哪个定界符.
Next when filter will remove all empty, or containing only spaces Strings we can collect
rest of elements. Thanks to Collectors.joining
we can decide which delimiter to use.
public static String implode(String separator, String... data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length - 1; i++) {
//data.length - 1 => to not add separator at the end
if (!data[i].matches(" *")) {//empty string are ""; " "; " "; and so on
sb.append(data[i]);
sb.append(separator);
}
}
sb.append(data[data.length - 1].trim());
return sb.toString();
}
您可以像使用它
System.out.println(implode(", ", "ab", " ", "abs"));
或
System.out.println(implode(", ", new String[] { "ab", " ", "abs" }));
输出ab, abs
这篇关于Java等价于PHP的implode(',',array_filter(array()))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!