番石榴乔伊纳没有前缀和后缀的能力 [英] Guava Joiner doesn't have ability to prefix and suffix

查看:99
本文介绍了番石榴乔伊纳没有前缀和后缀的能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如

  String str [] = {a,b,c}; 
Joiner.on(,)。prefix(')。suffix(')。join(str);






预期输出为:

 'a','b','c'

我们有其他的选择吗?由于番石榴不这样做(或我不知道)。使用java 8有更好的选择吗?

解决方案

您可以使用Guava的 List#transform 进行转换 a - > 'a',然后在转换的列表上使用 Joiner transform 只适用于 Iterable 对象,但不适用于数组。代码仍然很简洁:

  List< String> strList = Lists.newArraylist(str); // where str is your String [] 
Joiner.on(',')。join(Lists.transform(str,surroundWithSingleQuotes));

其中转换如下:

 函数< String,String> surroundWithSingleQuotes = new Function< String,String>(){
public String apply(String string){
return'+ string +';
}
};

有人可能会说这是一种啰嗦的做法,但我很佩服灵活性由 transform 范例提供。



编辑(因为现在有Java 8)



在Java 8中,所有这些都可以使用

  strList.stream()。map(s  - >'+ s +').collect(Collectors.joining(,)); 


I have requirement in Joiner to have the ability to prefix and suffix elements.

For example

String str[] = {"a", "b", "c"};
Joiner.on(",").prefix("'").suffix("'").join(str);


Expected output would be:

'a','b','c'

Do we have any alternative for this? As Guava doesn't do it (or I'm not aware of). With java 8 is there a better alternative?

解决方案

You can use Guava's List#transform to make the transformation a --> 'a' and then use Joiner on the transformed list. transform only works on Iterable objects, though, not on arrays. The code will still be succinct enough:

List<String> strList = Lists.newArraylist(str); // where str is your String[]
Joiner.on(',').join(Lists.transform(str, surroundWithSingleQuotes));

where the transformation is as follows:

Function<String, String> surroundWithSingleQuotes = new Function<String, String>() {
    public String apply(String string) {
        return "'" + string + "'";
    }
};

One might say this is a long-winded way of doing this, but I admire the amount of flexibility provided by the transform paradigm.

Edit (because now there's Java 8)

In Java 8, all this can be done in a single line using the Stream interface, as follows:

strList.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));

这篇关于番石榴乔伊纳没有前缀和后缀的能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆