简介
Guava是一种基于开源的Java库,这个库是为了方便编码,并减少编码错误。这个库用于提供集合,缓存,支持原语句,并发性,常见注解,字符串处理,I/O和验证的实用方法。
引包
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>11.0.2</version>
</dependency>
常用工具类
1.Lists,Sets
集合工具类
List list1 = Lists.newArrayList("element1","element2") //新建
Lists.partition(list1, 10) //拆分
Lists.reverse(list1) //反转排序
2.Preconditions 前置校验
前置条件适用于当判断与设置的条件不符合时,抛出异常的操作。
/**
* 对象判空处理
*/
UserInfo userInfo = null;
Preconditions.checkNotNull(userInfo, "userInfo不能为null");
/**
* List对象判空处理
*/
List<String> list = Lists.newArrayList();
Preconditions.checkNotNull(list, "传入的list不能为null");
/**
* 数值类型判断处理
*/
Long projectId = -12L;
Preconditions.checkNotNull(projectId, "projectId不能为null");
Preconditions.checkArgument(projectId > 0, "输入projectId必须大于0", projectId);
3.Splitter
Splitter可以对字符串进行分割,在分割时的方式有2种,
1.按字符/字符串分割
2.按正则进行分割
Splitter在分割完成时可以转换成list和map
1.按字符分隔
//1.用指定字符切分字符串,并转换成list
String s1 = "hello|hihi";
String s2 = "hello|haha|||";
Splitter.on("|").splitToList(s1).forEach(System.out::println);
Splitter.on("|").split(s1).forEach(item ->System.out.println(item));
//2.忽略掉空的字符串或者多余的分割符
Splitter.on("|").omitEmptyStrings().splitToList(s2).forEach(System.out::println);
//3.忽略掉字符串中的空格
Splitter.on("|").omitEmptyStrings().trimResults().splitToList("hello | guava|||").forEach(System.out::println);
//4.固定长度分割
Splitter.on("|").fixedLength(4).splitToList("aaaabbbbccccdddd").forEach(System.out::println);
//5.指定长度分割
List<String> list = Splitter.on("#").limit(3).splitToList("a#b#c#d#e#"); //以#来分割,分3部分成 a b #c#d#e 3部分
System.out.println(list.get(0));
System.out.println(list.get(1));
System.out.println(list.get(2));
2.按正则分隔
Pattern SPLIT_PATTERN = Pattern.compile("[\\,\\,\\s]+|\\|");
List<String> strings = Splitter.on(SPLIT_PATTERN).omitEmptyStrings().trimResults().splitToList(
"String,12,3");
4.Stopwatch
计时器,可用于记录某段代码or接口执行时间,替代用System.currentTimeMillis()相减。
Stopwatch watch = Stopwatch.createStarted();
Thread.sleep(1000L);
long time = watch.elapsed(TimeUnit.MILLISECONDS);
5.rateLimiter
用于接口限流
public static class LimitingCommpont {
RateLimiter rateLimiter;
String name;
public <T> T exec(Double limitCount,Long waitTime, RateLimiterFactory.Callback<T> callback) {
if (rateLimiter.getRate() != limitCount) {
rateLimiter.setRate(limitCount); //设置速率,每秒多少许可数
}
try {
//从RateLimiter 获取许可如果该许可可以在不超过timeout的时间内获取得到的话,或者如果无法在timeout 过期之前获取得到许可的话,那么立即返回false(无需等待)
rateLimiter.tryAcquire(waitTime, TimeUnit.SECONDS); //
} catch (Exception e) {
log.error("限流失败 {}", name);
}
log.info("每秒qps值 name : {} time : {} ", name, System.currentTimeMillis() / 1000);
return callback.apply();
}
}
6.Range
区间,也称为范围 ,通常可以用于时间、金额等范围判断。
1.区间创建
概念 | 表示范围 | guava对应功能方法 |
---|---|---|
(a..b) | {x | a < x < b} | open(C, C) |
[a..b] | {x | a <= x <= b} | closed(C, C) |
[a..b) | {x | a <= x < b} | closedOpen(C, C) |
(a..b] | {x | a < x <= b} | openClosed(C, C) |
(a..+∞) | {x | x > a} | greaterThan(C) |
[a..+∞) | {x | x >= a} | atLeast(C) |
(-∞..b) | {x | x < b} | lessThan(C) |
(-∞..b] | {x | x <= b} | atMost(C) |
(-∞..+∞) | all values | all() |
2.操作方法
//1.contains:判断值是否在当前Range内
Range.lessThan(4.0); //严格小于4.0的double值
Range.closed(1, 3).contains(2);//return true
Range.lessThan(5).contains(5); //return false
Range.closed(1, 4).containsAll(Ints.asList(1, 2, 3)); //return true
//2.isConnected。range是否可连接上
Range.closed(3, 5).isConnected(Range.open(5, 10));// true
Range.closed(0, 9).isConnected(Range.closed(3, 4));//true
Range.open(3, 5).isConnected(Range.open(5, 10));//false
Range.closed(1, 5).isConnected(Range.closed(6, 10));//false
3.案例
Date now = DateUtils.ceiling(new Date(), Calendar.DATE);
// 5天后
Date nowafter5day = DateUtils.addDays(now, 5);
// 6天后
Date nowafter6day = DateUtils.addDays(now, 6);
// 7天后
Date nowafter7day = DateUtils.addDays(now, 7);
// 8天后
Date nowafter8day = DateUtils.addDays(now, 8);
// 8天后
Date nowafter9day = DateUtils.addDays(now, 9);
// 10天后
Date nowafter10day = DateUtils.addDays(now, 10);
// 已有档期
Range planA = Range.openClosed(now, nowafter5day);
Range planB = Range.openClosed(nowafter8day, nowafter10day);
List<Range> existRangeList = Lists.newArrayList(planA, planB);
// 新计划
Range planNew = Range.openClosed(nowafter6day, nowafter7day);
int count = 0;
for (Range li : existRangeList) {
if (li.isConnected(planNew)) {
System.out.println("planNew["+planNew+"]档期重叠,校验不通过");
break;
}
++count;
}
if (count == existRangeList.size()) {
System.out.println("planNew["+planNew+"]通过校验");
existRangeList.add(planNew);
}
Range planNew2 = Range.openClosed(nowafter7day, nowafter9day);
count = 0;
for (Range li : existRangeList) {
if (li.isConnected(planNew2)) {
System.out.println("PlanNew2["+planNew2+"]档期重叠,校验不通过");
break;
}
++count;
}
if (count == existRangeList.size()) {
System.out.println("planNew2["+planNew2+"]通过校验");
existRangeList.add(planNew2);
}
网友评论