记录几个常用的工具类的常用方法
java.util.Objects
JDK 7后出现,提供静态方法操作对象。
public static boolean isNull(Object obj) {
return obj == null;
}
public static boolean nonNull(Object obj) {
return obj != null;
}
org.apache.commons.lang.StringUtils
1. 判断是否为一个数字
public static boolean isNumeric(String str) {
if (str == null) {
return false;
} else {
int sz = str.length();
for(int i = 0; i < sz; ++i) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
2. 判断字符串是否由字母组成
public static boolean isAlpha(String str) {
if (str == null) {
return false;
} else {
int sz = str.length();
for(int i = 0; i < sz; ++i) {
if (!Character.isLetter(str.charAt(i))) {
return false;
}
}
return true;
}
}
3. 剥离字符串,否则去掉字符串两边一样的字符,到不一样为止
public static String strip(String str, String stripChars) {
if (isEmpty(str)) {
return str;
} else {
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
}
使用strip去除list集合两端的[]
StringUtils.strip(appIdList.toString(),"[]")
4. 字符串判空,可以识别空字符串
public static boolean isBlank(String str) {
int strLen;
if (str != null && (strLen = str.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
5. 字符串判空,不能识别空字符串
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
java.util.Collections
用于操作Set、List和Map等集合,提供了大量方法对集合进行排序、查询和修改等操作,还提供了将集合对象置为不可变、对集合对象实现同步控制等方法。
这个类不需要创建对象,内部提供的都是静态方法。
1. 返回一个空的列表,不可变,开发中尽量避免返回null
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
2. 不可变,任何对它的更改,都会导致UnsupportedOperationException,因此,此list的容量始终为1
public static <T> List<T> singletonList(T o) {
return new SingletonList<>(o);
}
org.springframework.util.CollectionUtils
提供集合、Map、数组间的转换以及包含关系(交集、并集、差集)等操作。
1. 判断集合是否为空
public static boolean isEmpty(@Nullable Collection<?> collection) {
return collection == null || collection.isEmpty();
}
2. 判断map是否为空
public static boolean isEmpty(@Nullable Map<?, ?> map) {
return map == null || map.isEmpty();
}
还提供了ListUtils、SetUtils、MapUtil工具包。