- String
- 嘟嘟嘟
- 生成随机数
- 集合操作
- List集合
- 切分Lists.partition
- Map集合
- 过滤指定的key
- 获取map中的key - value值
- putIfAbsent和computeIfAbsent
- Set集合
- 交集(intersection)和差集(difference)
- Redis
- XX操作
- getBucket
参考链接
集合操作 List集合 切分Lists.partition将如下numList集合按指定长度进行切分,返回新的List>集合,如下的:
List lists=Lists.partition(numList,3);
package test;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.List;
public class testList {
@Test
public void test(){
List numList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List> lists=Lists.partition(numList,3);
System.out.println(lists); //[[1, 2, 3], [4, 5, 6], [7, 8]]
}
}
Lists.Partition 在项目中遇到的坑总结:
项目中使用 Lists.Partition 批量处理数据,但是最近内存一直 OutOffMemory,GC无法回收。
后来我们对使用过的集合手动 clear,没有测试直接就上线了。尴尬的是内存回收了,但是跑出来的数据出问题了。
最后自己单元测试发现是 List resultPartition = Lists.partition(list, 500) 之后再对 list 进行 clear 操作,resultPartition也会被清空。
回来谷歌才发现它最终会调用 list.subList。subList 执行结果是获取 ArrayList 的一部分,返回的是 ArrayList 的部分视图。
对子集合的操作会反映到原集合, 对原集合的操作也会影响子集合。
参考链接
Map集合 过滤指定的keyMapextendParam = alertMap.entrySet().stream() .filter(map -> "labels".equals(map.getKey()) || "annotations".equals(map.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
上述代码是,获取map中指定的key的map集合。只保留labels和annotations 键的数据,组成新的map。
获取map中的key - value值JDK1.8中map.forEach方式获取Map中的key,value
map.forEach((k,v)->{
});
putIfAbsent和computeIfAbsent
computeIfAbsent用的较多。
computeIfAbsent源码:
default V computeIfAbsent(K key,
Function super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}
putIfAbsent源码:
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
Set集合
交集(intersection)和差集(difference)
intersection()方法用于返回两个或更多集合中都包含的元素,即交集。
difference()函数用户返回两个集合的差集,即返回的在第一个集合但不在第二个集合中的元素
用法:
x={'a','b','c'}
y={'a','d','e'}
print(Sets.intersection(x,y));
//输出
{'a'}
print(x.difference(y));
//输出
{'b', 'c'}
Redis
XX操作
getBucket
用法:RedissonClient.getBucket方法
所在包类org.redisson.api.RedissonClient
//引入redissonClient
@Autowired
private RedissonClient redissonClient;
//设置缓存数据
SmsCaptchaVO smsCaptcha = new SmsCaptchaVO();
smsCaptcha.setCode(code);
smsCaptcha.setExpireDateTime(LocalDateTime.now().plusMinutes(30));
smsCaptcha.setResendDateTime(LocalDateTime.now().plusMinutes(1));
RBucket smsCaptchaBucket = redissonClient.getBucket(getKey(mobile));//设置某key的 RBucket
smsCaptchaBucket.set(new Gson().toJson(smsCaptcha));//设置对应key的值
//获取缓存数据
String smsCaptchaKey = getKey(mobile);
SmsCaptchaVO smsCaptcha = null;
RBucket smsCaptchaBucket = redissonClient.getBucket(smsCaptchaKey);
logger.info(smsCaptchaBucket.toString());
if (smsCaptchaBucket.isExists()) {
// 返回Redis数据
smsCaptcha = new Gson().fromJson(smsCaptchaBucket.get(), SmsCaptchaVO.class);
}
// 删除Redis 对应 数据 (失效掉)
redissonClient.getBucket(redisKey).delete();



