# 这17个小工具，让我的开发效率提升了50%

49,970

## 1. Collections

### 1.1 排序

``````  List<Integer> list = new ArrayList<>();
Collections.sort(list);//升序
System.out.println(list);
Collections.reverse(list);//降序
System.out.println(list);
``````

``````[1, 2, 3]
[3, 2, 1]
``````

### 1.2 获取最大或最小值

``````List<Integer> list = new ArrayList<>();
Integer max = Collections.max(list);//获取最大值
Integer min = Collections.min(list);//获取最小值
System.out.println(max);
System.out.println(min);
``````

``````3
1
``````

### 1.3 转换线程安全集合

``````  List<Integer> list = new ArrayList<>();

List<Integer> integers = Collections.synchronizedList(list);//将ArrayList转换成线程安全集合
System.out.println(integers);
``````

### 1.4 返回空集合

``````private List<Integer> fun(List<Integer> list) {
if (list == null || list.size() == 0) {
return Collections.emptyList();
}
//业务处理
return list;
}
``````

### 1.5 二分查找

`binarySearch`方法提供了一个非常好用的`二分查找`功能，只用传入指定集合和需要找到的key即可。例如：

``````List<Integer> list = new ArrayList<>();

int i = Collections.binarySearch(list, 3);//二分查找
System.out.println(i );
``````

``````2
``````

### 1.6 转换成不可修改集合

``````List<Integer> list = new ArrayList<>();

List<Integer> integers = Collections.unmodifiableList(list);
System.out.println(integers);
``````

``````Exception in thread "main" java.lang.UnsupportedOperationException
at com.sue.jump.service.test1.UtilTest.main(UtilTest.java:19)
``````

## 2. CollectionUtils

`apache``org.apache.commons.collections`包下的CollectionUtils工具类。

### 2.1 集合判空

``````List<Integer> list = new ArrayList<>();

if (CollectionUtils.isEmpty(list)) {
System.out.println("集合为空");
}

if (CollectionUtils.isNotEmpty(list)) {
System.out.println("集合不为空");
}
``````

### 2.2 对两个集合进行操作

``````List<Integer> list = new ArrayList<>();

List<Integer> list2 = new ArrayList<>();

//获取并集
Collection<Integer> unionList = CollectionUtils.union(list, list2);
System.out.println(unionList);

//获取交集
Collection<Integer> intersectionList = CollectionUtils.intersection(list, list2);
System.out.println(intersectionList);

//获取交集的补集
Collection<Integer> disjunctionList = CollectionUtils.disjunction(list, list2);
System.out.println(disjunctionList);

//获取差集
Collection<Integer> subtractList = CollectionUtils.subtract(list, list2);
System.out.println(subtractList);
``````

``````[1, 2, 3, 4]
[2]
[1, 3, 4]
[1, 3]
``````

## 3. Lists

### 3.1 创建空集合

``````List<Integer> list = Lists.newArrayList();
``````

### 3.2 快速初始化集合

``````List<Integer> list = Lists.newArrayList(1, 2, 3);
``````

``````[1, 2, 3]
``````

### 3.3 笛卡尔积

``````List<Integer> list1 = Lists.newArrayList(1, 2, 3);
List<Integer> list2 = Lists.newArrayList(4,5);
List<List<Integer>> productList = Lists.cartesianProduct(list1,list2);
System.out.println(productList);
``````

``````[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
``````

### 3.4 分页

``````List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> partitionList = Lists.partition(list, 2);
System.out.println(partitionList);
``````

``````[[1, 2], [3, 4], [5]]
``````

### 3.5 流处理

``````List<String> list = Lists.newArrayList("a","b","c");
List<String> transformList = Lists.transform(list, x -> x.toUpperCase());
System.out.println(transformList);
``````

### 3.6 颠倒顺序

Lists的有颠倒顺序的方法`reverse`。例如：

``````List<Integer> list = Lists.newArrayList(3, 1, 2);
List<Integer> reverseList = Lists.reverse(list);
System.out.println(reverseList);
``````

``````[2, 1, 3]
``````

list的原始顺序是312，使用`reverse`方法颠倒顺序之后，变成了213。

Lists还有其他的好用的工具，我在这里只是抛砖引玉，有兴趣的朋友，可以仔细研究一下。

## 4. Objects

`jdk7`之后，提供了`Objects`工具类，我们可以通过它操作对象。

### 4.1 对象判空

``````Integer integer = new Integer(1);

if (Objects.isNull(integer)) {
System.out.println("对象为空");
}

if (Objects.nonNull(integer)) {
System.out.println("对象不为空");
}
``````

### 4.2 对象为空抛异常

``````Integer integer1 = new Integer(128);

Objects.requireNonNull(integer1);
Objects.requireNonNull(integer1, "参数不能为空");
Objects.requireNonNull(integer1, () -> "参数不能为空");
``````

### 4.3 判断两个对象是否相等

``````Integer integer1 = new Integer(1);
Integer integer2 = new Integer(1);

System.out.println(Objects.equals(integer1, integer2));
``````

``````true
``````

``````Integer integer1 = new Integer(1);
Long integer2 = new Long(1);

System.out.println(Objects.equals(integer1, integer2));
``````

``````false
``````

### 4.4 获取对象的hashCode

``````String str = new String("abc");
System.out.println(Objects.hashCode(str));
``````

``````96354
``````

Objects的内容先介绍到这里，有兴趣的小伙们，可以看看下面更多的方法：

## 5. BooleanUtils

### 5.1 判断true或false

``````Boolean aBoolean = new Boolean(true);
System.out.println(BooleanUtils.isTrue(aBoolean));
System.out.println(BooleanUtils.isFalse(aBoolean));
``````

### 5.2 判断不为true或不为false

``````Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = null;
System.out.println(BooleanUtils.isNotTrue(aBoolean));
System.out.println(BooleanUtils.isNotTrue(aBoolean1));
System.out.println(BooleanUtils.isNotFalse(aBoolean));
System.out.println(BooleanUtils.isNotFalse(aBoolean1));
``````

``````false
true
true
true
``````

### 5.3 转换成数字

``````Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = new Boolean(false);
System.out.println(BooleanUtils.toInteger(aBoolean));
System.out.println(BooleanUtils.toInteger(aBoolean1));
``````

``````1
0
``````

### 5.4 Boolean转换成布尔值

``````Boolean aBoolean = new Boolean(true);
Boolean aBoolean1 = null;
System.out.println(BooleanUtils.toBoolean(aBoolean));
System.out.println(BooleanUtils.toBoolean(aBoolean1));
System.out.println(BooleanUtils.toBooleanDefaultIfNull(aBoolean1, false));
``````

BooleanUtils类的方法还有很多，有兴趣的小伙伴可以看看下面的内容：

## 6. StringUtils

`字符串`（String）在我们的日常工作中，用得非常非常非常多。

### 6.1 字符串判空

StringUtils给我们提供了多个判空的静态方法，例如：

`````` String str1 = null;
String str2 = "";
String str3 = " ";
String str4 = "abc";
System.out.println(StringUtils.isEmpty(str1));
System.out.println(StringUtils.isEmpty(str2));
System.out.println(StringUtils.isEmpty(str3));
System.out.println(StringUtils.isEmpty(str4));
System.out.println("=====");
System.out.println(StringUtils.isNotEmpty(str1));
System.out.println(StringUtils.isNotEmpty(str2));
System.out.println(StringUtils.isNotEmpty(str3));
System.out.println(StringUtils.isNotEmpty(str4));
System.out.println("=====");
System.out.println(StringUtils.isBlank(str1));
System.out.println(StringUtils.isBlank(str2));
System.out.println(StringUtils.isBlank(str3));
System.out.println(StringUtils.isBlank(str4));
System.out.println("=====");
System.out.println(StringUtils.isNotBlank(str1));
System.out.println(StringUtils.isNotBlank(str2));
System.out.println(StringUtils.isNotBlank(str3));
System.out.println(StringUtils.isNotBlank(str4));
``````

``````true
true
false
false
=====
false
false
true
true
=====
true
true
true
false
=====
false
false
false
true
``````

### 6.2 分隔字符串

``````String str1 = null;
System.out.println(StringUtils.split(str1,","));
System.out.println(str1.split(","));
``````

``````null
at com.sue.jump.service.test1.UtilTest.main(UtilTest.java:21)
``````

### 6.3 判断是否纯数字

``````String str1 = "123";
String str2 = "123q";
String str3 = "0.33";
System.out.println(StringUtils.isNumeric(str1));
System.out.println(StringUtils.isNumeric(str2));
System.out.println(StringUtils.isNumeric(str3));
``````

``````true
false
false
``````

### 6.4 将集合拼接成字符串

``````List<String> list = Lists.newArrayList("a", "b", "c");
List<Integer> list2 = Lists.newArrayList(1, 2, 3);
System.out.println(StringUtils.join(list, ","));
System.out.println(StringUtils.join(list2, " "));
``````

``````a,b,c
1 2 3
``````

## 7. Assert

### 7.1 断言参数是否为空

``````String str = null;
Assert.isNull(str, "str必须为空");
Assert.isNull(str, () -> "str必须为空");
Assert.notNull(str, "str不能为空");
``````

### 7.2 断言集合是否为空

``````List<String> list = null;
Map<String, String> map = null;
Assert.notEmpty(list, "list不能为空");
Assert.notEmpty(list, () -> "list不能为空");
Assert.notEmpty(map, "map不能为空");
``````

### 7.3 断言条件是否为空

``````List<String> list = null;
Assert.isTrue(CollectionUtils.isNotEmpty(list), "list不能为空");
Assert.isTrue(CollectionUtils.isNotEmpty(list), () -> "list不能为空");
``````

## 8. IOUtils

`IO`流在我们日常工作中也用得比较多，尽管java已经给我们提供了丰富的API。

### 8.1 读取文件

``````String str = IOUtils.toString(new FileInputStream("/temp/a.txt"), StandardCharsets.UTF_8);
System.out.println(str);
``````

### 8.2 写入文件

``````String str = "abcde";
IOUtils.write(str, new FileOutputStream("/temp/b.tx"), StandardCharsets.UTF_8);
``````

### 8.3 文件拷贝

``````IOUtils.copy(new FileInputStream("/temp/a.txt"), new FileOutputStream("/temp/b.txt"));
``````

### 8.4 读取文件内容到字节数组

``````byte[] bytes = IOUtils.toByteArray(new FileInputStream("/temp/a.txt"));
``````

IOUtils类非常实用，感兴趣的小伙们，可以看看下面内容。

## 9. MDC

`MDC``org.slf4j`包下的一个类，它的全称是Mapped Diagnostic Context，我们可以认为它是一个线程安全的存放诊断日志的容器。

MDC的底层是用了`ThreadLocal`来保存数据的。

``````public class LogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("记录请求日志");
chain.doFilter(request, response);
System.out.println("记录响应日志");
}

@Override
public void destroy() {
}
}
``````

``````public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
return execution.execute(request, body);
}
}
``````

``````@Configuration
public class RestTemplateConfiguration {

@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));
return restTemplate;
}

@Bean
public RestTemplateInterceptor restTemplateInterceptor() {
return new RestTemplateInterceptor();
}
}
``````

``````public class MdcUtil {

private static final String TRACE_ID = "TRACE_ID";

public static String get() {
return MDC.get(TRACE_ID);
}

public static void add(String value) {
MDC.put(TRACE_ID, value);
}
}
``````

## 10. ClassUtils

spring的`org.springframework.util`包下的`ClassUtils`类，它里面有很多让我们惊喜的功能。

### 10.1 获取对象的所有接口

``````Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(new User());
``````

### 10.2 获取某个类的包名

``````String packageName = ClassUtils.getPackageName(User.class);
System.out.println(packageName);
``````

### 10.3 判断某个类是否内部类

``````System.out.println(ClassUtils.isInnerClass(User.class));
``````

### 10.4 判断对象是否代理对象

``````System.out.println(ClassUtils.isCglibProxy(new User()));
``````

ClassUtils还有很多有用的方法，等待着你去发掘。感兴趣的朋友，可以看看下面内容：

## 11. BeanUtils

spring给我们提供了一个`JavaBean`的工具类，它在`org.springframework.beans`包下面，它的名字叫做：`BeanUtils`

### 11.1 拷贝对象的属性

``````User user1 = new User();
user1.setId(1L);
user1.setName("苏三说技术");

User user2 = new User();
BeanUtils.copyProperties(user1, user2);
System.out.println(user2);
``````

### 11.2 实例化某个类

``````User user = BeanUtils.instantiateClass(User.class);
System.out.println(user);
``````

### 11.3 获取指定类的指定方法

``````Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
System.out.println(declaredMethod.getName());
``````

### 11.4 获取指定方法的参数

``````Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
PropertyDescriptor propertyForMethod = BeanUtils.findPropertyForMethod(declaredMethod);
System.out.println(propertyForMethod.getName());
``````

## 12. ReflectionUtils

### 12.1 获取方法

``````Method method = ReflectionUtils.findMethod(User.class, "getId");
``````

### 12.2 获取字段

``````Field field = ReflectionUtils.findField(User.class, "id");
``````

### 12.3 执行方法

`````` ReflectionUtils.invokeMethod(method, springContextsUtil.getBean(beanName), param);
``````

### 12.4 判断字段是否常量

``````Field field = ReflectionUtils.findField(User.class, "id");
System.out.println(ReflectionUtils.isPublicStaticFinal(field));
``````

### 12.5 判断是否equals方法

``````Method method = ReflectionUtils.findMethod(User.class, "getId");
System.out.println(ReflectionUtils.isEqualsMethod(method));
``````

## 13. Base64Utils

``````String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("加密后：" + encode);
try {
String decode = new String(Base64Utils.decode(encode.getBytes()), "utf8");
System.out.println("解密后：" + decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
``````

``````加密后：YWJj

``````

## 14. StandardCharsets

``````String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("加密后：" + encode);
String decode = new String(Base64Utils.decode(encode.getBytes())
, StandardCharsets.UTF_8);
System.out.println("解密后：" + decode);
``````

## 15. DigestUtils

### 15.1 md5加密

``````String md5Hex = DigestUtils.md5Hex("苏三说技术");
System.out.println(md5Hex);
``````

### 15.2 sha256加密

``````String md5Hex = DigestUtils.sha256Hex("苏三说技术");
System.out.println(md5Hex);
``````

## 16. SerializationUtils

``````Map<String, String> map = Maps.newHashMap();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
byte[] serialize = SerializationUtils.serialize(map);
Object deserialize = SerializationUtils.deserialize(serialize);
System.out.println(deserialize);
``````

## 17. HttpStatus

``````private int SUCCESS_CODE = 200;
private int ERROR_CODE = 500;
private int NOT_FOUND_CODE = 404;
``````