guava深入理解(3)-字符串,实用方法,函数式编程

字符串处理

Joiner是用来拼接转化集合到字符串的(其实很多动态语言基本上没有太区分字符串和普通集合,很多在集合上能用的方法在字符串上也能用,字符串本来就就是个字符数组)

Joiner.on("|").skipNulls().join(new Integer[]{1,2,3,4});
Joiner.on("|").useForNull("no value").join(stringList)

//joiner类和java的pattern差不多,创建之后可以多次使用
Joiner stringJoiner = Joiner.on("|").skipNulls();
stringJoiner.join("foo","bar",null);

//joiner还可以用来处理map
String expectedString = "Washington D.C=Redskins#New York
City=Giants#Philadelphia=Eagles#Dallas=Cowboys";
Map<String,String> testMap = Maps.newLinkedHashMap();
testMap.put("Washington D.C","Redskins");
testMap.put("New York City","Giants");
testMap.put("Philadelphia","Eagles");
testMap.put("Dallas","Cowboys");
String returnedString = Joiner.on("#").
withKeyValueSeparator("=").join(testMap);
assertThat(returnedString,is(expectedString));

spitter类是相反的转换,从字符串到集合

//转换
Splitter.on('|').split("foo|bar|baz");
//用正则来分割
Splitter splitter = Splitter.on("\\d+");
//删除多余的空格
Splitter splitter = Splitter.on('|').trimResults();
//字符串转换成map
String startString = "Washington D.C=Redskins#New York
City=Giants#Philadelphia=Eagles#Dallas=Cowboys";
Map<String,String> testMap = Maps.newLinkedHashMap();
testMap.put("Washington D.C","Redskins");
testMap.put("New York City","Giants");
testMap.put("Philadelphia","Eagles");
testMap.put("Dallas","Cowboys");
Splitter.MapSplitter mapSplitter =
Splitter.on("#").withKeyValueSeparator("=");
Map<String,String> splitMap =
mapSplitter.split(startSring);
assertThat(testMap,is(splitMap));

guava还有很多和字符串有关的功能,不过我觉得就这两个最有用,其他的一些对字符串本身的操作,例如替换,删除某些字符,还是直接用正则表达式来的更快,更清晰。

当然,java对正则表达式的处理稍显麻烦,所以这里还是要安利一发kotlin,使用正则表达式更加方便。

对象实用方法

guava还提供了很多实用的方法
toString

public String toString() {
return Objects.toStringHelper(this)
.omitNullValues()
.add("title", title)
.add("author", author)
.add("publisher", publisher)
.add("price",price)
.add("isbn", isbn).toString();
}

hashcode

public int hashCode() {
return Objects.hashCode(title, author, publisher, isbn);
}

compareTo

public int compareTo(Book o) {
return ComparisonChain.start()
.compare(this.title, o.getTitle())
.compare(this.author, o.getAuthor())
.compare(this.publisher, o.getPublisher())
.compare(this.isbn, o.getIsbn())
.compare(this.price, o.getPrice())
.result();
}

当然,时至今日,现在这些方法已经完全可以用ide来处理,使用guava反而有时更加麻烦。具体怎么选择还是看自己的喜好吧。

函数式编程支持

这个其实也没什么好讲的,就是加了几个接口,但是现在不仅java8已经自带了那些接口,还有强大的rxjava可以使用(强烈安利一发)。guava自己都把一些原来使用它自带的那些接口方法修饰成过时方法了,所以其实没什么好用的了。

如果要找函数式编程的框架,就用rxjava吧。


欢迎关注我的github
https://github.com/luckyCatMiao

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值