Java基础

合并数组为String并插入分隔符

1
StringUtils.join(Arrarys.asList(T... a),"-");

List过大时拆批处理(guava包)

1
Lists.partition(List<T> list, int size).forEach(subList->doMethod(subList));

通过Stream List转List

1
2
3
List<Integer> list = otherList.stream().map(subInt->{
return new Integer(1);
}).collect(Collectors.toList());

近端缓存(guava包)

示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@Component
public class LocalCacheHelper {

@Value("${localCache.expireTime:60}")
private Integer expireTime;

@Value("${localCache.maxSize:2000}")
private Integer maxSize;

private static Cache<String, String> cache;


@PostConstruct
private void init() {

//创建一个LoadingCache,并可以进行一些简单的缓存配置
cache = CacheBuilder.newBuilder()
//最大容量为100(基于容量进行回收)
.maximumSize(maxSize)
//配置写入后多久使缓存过期
.expireAfterWrite(expireTime, TimeUnit.MINUTES)
.recordStats()
.build();
}

public static <T>String get(String key, Supplier<T> supplier,UmsLogger logger) {
try {
logger.build("key", key);
return cache.get(key, () -> {
logger.info("do not use cache");
return JSON.toJSONString(supplier.get());
});
} catch (ExecutionException e) {
logger.error(e.getMessage());
}
return null;
}

public static void put(String key, Object value) {
String v = JSON.toJSONString(value);
cache.put(key, v);
}
}

POJO转换工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* pojo转换工具类
*
* @author lich.wangy
* @date 2018-11-08
*/
public class ModelConvertUtils {

/**
* 把source对象的属性复制到result对象中
*
* 例如将A a 转为B b
* B b = PojoConvertUtils.convert(a,B.class);
*
* @param source
* @param s
* @param <R>
* @param <S>
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static <R, S> R convert(S source, Supplier<R> s) {
if (source == null) {
return null;
}
R result = s.get();
BeanUtils.copyProperties(source, result);
return result;

}

/**
* 把source对象列表复制到result对象列表
* * 例如将List<A> a 转为List<B> b
* List<B> b = PojoConvertUtils.convert(a,B.class);
*
* @param sourceList
* @param supplier
* @param <R>
* @param <S>
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static <R, S> List<R> convert(List<S> sourceList, Supplier<R> supplier) {
if (sourceList == null) {
return null;
}
return sourceList.stream().map(each -> convert(each, supplier)).collect(Collectors.toList());
}


}