Guava
一个非常有意思的,来自google的工具,maven依赖如下:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
字符串与对象
- Joiner(连接,list、map连接)
- Splitter/MapSplitter(分割器,字符串按照格式分割成list或map)
- Strings类(判空,重复,填充,公共前缀)
- CharMatcher(字符串格式化,字符串抽取)
- Preconditions(checkNotNull,检查下标,参数,状态)
- MoreObjects(tostring,hashcode重写,ComparisonChain.start()比较器)
Map map= Maps.newLinkedHashMap();
map.putIfAbsent("testA","1234");
map.putIfAbsent("testB","4567");
//1.joiner
String result=Joiner.on("#").withKeyValueSeparator("=").join(map);
//testA=1234#testB=4567
List<String> lt = Arrays.asList("123", "456");
String result2=Joiner.on("+").join(lt);
//123+456
Splitter.on("|").split("foo|bar|baz").forEach(System.out::println);
String startString = "Washington D.C=Redskins#New York City=Giants#Philadelphia=Eagles#Dallas=Cowboys";
Splitter.MapSplitter mapSplitter =Splitter.on("#").withKeyValueSeparator("=");
Map<String,String> splitMap = mapSplitter.split(startString);
//{Washington D.C=Redskins, New York City=Giants, Philadelphia=Eagles, Dallas=Cowboys}
String testString = "helloLk";
boolean isNullOrEmpty=Strings.isNullOrEmpty(testString);
String lettersAndNumbers = "foo989yxbar234";
String expected = "989234";
String retained = CharMatcher.digit().retainFrom(lettersAndNumbers);
assertEquals(expected,retained);
//true
Preconditions.checkNotNull(testString, "XXX is null");
MoreObjects.toStringHelper(splitMap).add("test","1234").toString();
函数式编程
- Function<F,T>接口,使用函数达到目的而不是改变状态,转换对象,隐藏实现
- 匿名内部类也能实现,但是较为笨重
- Functions.forMap处理map和Functions.compose流式处理
- Predicate
接口,断言,Predicates.and/or/not/compose - Supplier
接口,抽象了复杂性和对象如何建立的细节,Suppliers.memoize返回缓存的代理实例
Suppliers.memoizeWithExpiration,带有消亡时间的缓存代理实例
//函数接口,指定in和out类型,apply实现函数
public interface Function<F,T> {
T apply(F input);
boolean equals(Object object);
}
public class DateFormatFunction implements Function<Date,String> {
@Override
public String apply(Date input) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
return dateFormat.format(input);
}
}
public interface Predicate<T> {
boolean apply(T input)
boolean equals(Object object)
}
public interface Supplier<T> {
T get();
}
缓存
- MapMaker类,使用fluent接口API构造CHM
ConcurrentMap<String,Book> books = new MapMaker()
.concurrencyLevel(2)
.softValues()
.makeMap();
- Cache和LoadingCache接口,常用方式如下:
LoadingCache<String,TradeAccount> tradeAccountCache =
CacheBuilder.newBuilder()
.expireAfterWrite(5L, TimeUnit.Minutes)
.maximumSize(5000L)
.softValues()//软饮用,回收
.removalListener(new TradeAccountRemovalListener())
.ticker(Ticker.systemTicker())
.build(new CacheLoader<String, TradeAccount>() {
@Override
public TradeAccount load(String key) throws Exception {
return tradeAccountService.getTradeAccountById(key);
}
});