java implode函数,Java等价于PHP的implode(',',array_filter(array()))

这篇博客探讨了如何在Java中实现类似PHP的字符串连接功能,即去除空值并用逗号分隔字符串。提供了两种Java 8的解决方案,一种使用StringJoiner和Pattern,另一种使用Stream和Predicate。这两种方法都避免了额外的逗号,并能处理没有元素的情况。
摘要由CSDN通过智能技术生成

I often use this piece of code in PHP

$ordine['address'] = implode(', ', array_filter(array($cliente['cap'], $cliente['citta'], $cliente['provincia'])));

It clears empty strings and join them with a ",". If only one remains it doesn't add an extra unneeded comma. It doesn't add a comma at the end. If none remains it returns empty string.

Thus I can get one of the following results

""

"Street abc 14"

"Street abc 14, 00168"

"Street abc 14, 00168, Rome"

What is the best Java implementation (less code) in Java without having to add external libraries (designing for Android)?

解决方案

Updated version using Java 8 (original at the end of post)

If you don't need to filter any elements you can use

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 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));

}

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.

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 " ").

So we can use

Pattern.compile("\\S").asPredicate();

or possibly little more descriptive, negation of strings which are only spaces, or empty

Pattern.compile("^\\s*$").asPredicate().negate();

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.

Original answer (before Java 8)

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();

}

You can use it like

System.out.println(implode(", ", "ab", " ", "abs"));

or

System.out.println(implode(", ", new String[] { "ab", " ", "abs" }));

Output ab, abs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值