一、树状结构工具类
package com.jowell.common.tree;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.beans.BeanMap;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class TreeUtils {
private TreeUtils() {
}
private static final TreeNodeConfig DEFAULT_CONFIG = createConfig(null, null, "sort"
, null, null);
public static <T, E> List<Tree<E>> transform(List<T> treeDemoList, E rootId, TreeNodeConfig config) {
if (CollectionUtils.isNotEmpty(treeDemoList)) {
return TreeUtil.build(treeDemoList, rootId, config, (object, tree) -> {
Map<String, T> map = BeanMap.create(object);
for (Map.Entry<String, T> entry : map.entrySet()) {
tree.putExtra(entry.getKey(), entry.getValue());
}
});
}
return Lists.newArrayList();
}
public static <T, E> List<Tree<E>> transform(List<T> treeDemoList, E rootId) {
return transform(treeDemoList, rootId, DEFAULT_CONFIG);
}
public static <T, K> List<T> childToParent(List<T> treeDemoList, T node, Function<? super T, ? extends K> idMapper
, Function<? super T, ? extends K> parentIdMapper) {
if (CollectionUtils.isNotEmpty(treeDemoList)) {
final Set<T> nodeList = new HashSet<>();
Map<? extends K, T> allMap = treeDemoList.stream().collect(
Collectors.toMap(idMapper, Function.identity(), (v1, v2) -> v2)
);
findParent(nodeList, node, allMap, parentIdMapper);
return new ArrayList<>(nodeList);
}
return Lists.newArrayList();
}
public static <T, E> Tree<E> parentToChile(List<T> treeDemoList, E id, E rootId) {
return parentToChile(transform(treeDemoList, rootId), id);
}
public static <E> Tree<E> parentToChile(List<Tree<E>> build, E id) {
Tree<E> childNode = new Tree<>();
if (CollectionUtils.isNotEmpty(build)) {
for (Tree<E> node : build) {
childNode = TreeUtil.getNode(node, id);
if (Objects.nonNull(childNode)) {
break;
}
}
}
return childNode;
}
private static <T, K> void findParent(Set<T> nodeList, T current, Map<? extends K, T> allMap
, Function<? super T, ? extends K> parentIdMapper) {
if (Objects.nonNull(current)) {
nodeList.add(current);
}
if (Objects.nonNull(current)) {
findParent(nodeList, allMap.get(parentIdMapper.apply(current)), allMap, parentIdMapper);
}
}
private static TreeNodeConfig createConfig(String idKey, String parentIdKey, String weighKey
, String childrenKey, Integer deep) {
TreeNodeConfig config = new TreeNodeConfig();
if (StringUtils.isNotBlank(idKey)) {
config.setIdKey(idKey);
}
if (StringUtils.isNotBlank(parentIdKey)) {
config.setParentIdKey(parentIdKey);
}
if (StringUtils.isNotBlank(weighKey)) {
config.setWeightKey(weighKey);
}
if (StringUtils.isNotBlank(childrenKey)) {
config.setChildrenKey(childrenKey);
}
if (deep != null) {
config.setDeep(deep);
}
return config;
}
}
1、数据库设计,一般也就这样设计的
2、代码实例
3、测试结果
二、参数校验断言工具类
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.Assert;
import java.util.Collection;
public class PaAssert {
private PaAssert() {
}
public static void isTrue(boolean condition, String miss) {
Assert.isTrue(condition, miss);
}
public static void notNull(Object obj, String paramName) {
Assert.notNull(obj, convertMessage(paramName));
}
public static void notBlank(String obj, String paramName) {
Assert.isTrue(obj != null && !obj.equals(""), convertMessage(paramName));
}
public static void notData(Object obj) {
Assert.notNull(obj, "查无数据");
}
public static void notData(Object obj, String sourceName) {
Assert.notNull(obj, "查无[" + sourceName + "]数据");
}
public static void isCeNotEmpty(Collection<?> cel, String paramName) {
Assert.isTrue(CollectionUtils.isNotEmpty(cel), convertMessage(paramName));
}
private static String convertMessage(String paramName) {
return "[" + paramName + "]参数缺失";
}
}
三、StringUtil工具类
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.geesun.common.constant.Constants;
import com.geesun.common.core.text.StrFormatter;
import com.geesun.common.exception.base.BaseException;
import org.springframework.util.AntPathMatcher;
import org.apache.commons.lang3.StringUtils
public class StringUtils extends StringUtils
{
private static final String NULLSTR = "";
private static final char SEPARATOR = '_';
public static <T> T nvl(T value, T defaultValue)
{
return value != null ? value : defaultValue;
}
public static boolean isEmpty(Collection<?> coll)
{
return isNull(coll) || coll.isEmpty();
}
public static boolean isNotEmpty(Collection<?> coll)
{
return !isEmpty(coll);
}
public static boolean isEmpty(Object[] objects)
{
return isNull(objects) || (objects.length == 0);
}
public static boolean isNotEmpty(Object[] objects)
{
return !isEmpty(objects);
}
public static boolean isEmpty(Map<?, ?> map)
{
return isNull(map) || map.isEmpty();
}
public static boolean isNotEmpty(Map<?, ?> map)
{
return !isEmpty(map);
}
public static boolean isEmpty(String str)
{
return isNull(str) || NULLSTR.equals(str.trim());
}
public static String isBlank(String str,String msg)
{
if (isNull(str) || NULLSTR.equals(str.trim())){
throw new BaseException(msg);
} else {
return str;
}
}
public static String isEmpty(String str,String messagse)
{
if (isNull(str) || NULLSTR.equals(str.trim())){
return messagse;
} else {
return str;
}
}
public static boolean isNotEmpty(String str)
{
return !isEmpty(str);
}
public static boolean isNull(Object object)
{
return object == null;
}
public static boolean isNotNull(Object object)
{
return !isNull(object);
}
public static boolean isArray(Object object)
{
return isNotNull(object) && object.getClass().isArray();
}
public static String trim(String str)
{
return (str == null ? "" : str.trim());
}
public static String substring(final String str, int start)
{
if (str == null)
{
return NULLSTR;
}
if (start < 0)
{
start = str.length() + start;
}
if (start < 0)
{
start = 0;
}
if (start > str.length())
{
return NULLSTR;
}
return str.substring(start);
}
public static String substring(final String str, int start, int end)
{
if (str == null)
{
return NULLSTR;
}
if (end < 0)
{
end = str.length() + end;
}
if (start < 0)
{
start = str.length() + start;
}
if (end > str.length())
{
end = str.length();
}
if (start > end)
{
return NULLSTR;
}
if (start < 0)
{
start = 0;
}
if (end < 0)
{
end = 0;
}
return str.substring(start, end);
}
public static String format(String template, Object... params)
{
if (isEmpty(params) || isEmpty(template))
{
return template;
}
return StrFormatter.format(template, params);
}
public static boolean ishttp(String link)
{
return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);
}
public static final Set<String> str2Set(String str, String sep)
{
return new HashSet<String>(str2List(str, sep, true, false));
}
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim)
{
List<String> list = new ArrayList<String>();
if (StringUtils.isEmpty(str))
{
return list;
}
if (filterBlank && StringUtils.isBlank(str))
{
return list;
}
String[] split = str.split(sep);
for (String string : split)
{
if (filterBlank && StringUtils.isBlank(string))
{
continue;
}
if (trim)
{
string = string.trim();
}
list.add(string);
}
return list;
}
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences)
{
if (isEmpty(cs) || isEmpty(searchCharSequences))
{
return false;
}
for (CharSequence testStr : searchCharSequences)
{
if (containsIgnoreCase(cs, testStr))
{
return true;
}
}
return false;
}
public static String toUnderScoreCase(String str)
{
if (str == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
boolean preCharIsUpperCase = true;
boolean curreCharIsUpperCase = true;
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (i > 0)
{
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1))
{
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
{
sb.append(SEPARATOR);
}
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
public static boolean inStringIgnoreCase(String str, String... strs)
{
if (str != null && strs != null)
{
for (String s : strs)
{
if (str.equalsIgnoreCase(trim(s)))
{
return true;
}
}
}
return false;
}
public static String convertToCamelCase(String name)
{
StringBuilder result = new StringBuilder();
if (name == null || name.isEmpty())
{
return "";
}
else if (!name.contains("_"))
{
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
String[] camels = name.split("_");
for (String camel : camels)
{
if (camel.isEmpty())
{
continue;
}
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
public static String toCamelCase(String s)
{
if (s == null)
{
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c == SEPARATOR)
{
upperCase = true;
}
else if (upperCase)
{
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
sb.append(c);
}
}
return sb.toString();
}
public static boolean matches(String str, List<String> strs)
{
if (isEmpty(str) || isEmpty(strs))
{
return false;
}
for (String pattern : strs)
{
if (isMatch(pattern, str))
{
return true;
}
}
return false;
}
public static boolean isMatch(String pattern, String url)
{
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj)
{
return (T) obj;
}
public static final String padl(final Number num, final int size)
{
return padl(num.toString(), size, '0');
}
public static final String padl(final String s, final int size, final char c)
{
final StringBuilder sb = new StringBuilder(size);
if (s != null)
{
final int len = s.length();
if (s.length() <= size)
{
for (int i = size - len; i > 0; i--)
{
sb.append(c);
}
sb.append(s);
}
else
{
return s.substring(len - size, len);
}
}
else
{
for (int i = size; i > 0; i--)
{
sb.append(c);
}
}
return sb.toString();
}
}
四、校验正则表达式工具类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;
public class RegexUtil {
private RegexUtil(){}
private static String REGEX_PHONE = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
private static String REGEX_NUMBER = "^[0-9]*[1-9][0-9]*$";
private static String REGEX_EMAIL = "^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$\n";
public static boolean regexPhone(String phone) {
if ((phone != null) && (!phone.isEmpty())) {
return Pattern.matches(REGEX_PHONE, phone);
}
return false;
}
public static boolean regexNumber(String number) {
if ((number != null) && (!number.isEmpty())) {
return Pattern.matches(REGEX_NUMBER, number);
}
return false;
}
public static boolean isValidEmail(String email) {
if ((email != null) && (!email.isEmpty())) {
return Pattern.matches(REGEX_EMAIL, email);
}
return false;
}
public static boolean idCardVerify(String idCard) {
if (idCard.length() != 18) {
return false;
}
idCard = idCard.toUpperCase();
char[] idCardChars = idCard.toCharArray();
final int[] factors = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
int sumFactor = 0;
for (int i = 0; i < factors.length; i++) {
int value = idCardChars[i] - 48;
if (value < 0 || value > 9) {
return false;
}
sumFactor += factors[i] * value;
}
final char[] verifyCode = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
return idCardChars[17] == verifyCode[sumFactor % 11];
}
public static boolean isValidDate(String inDate) {
if (inDate == null) {
return false;
}
SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMdd");
if (inDate.trim().length() != dataFormat.toPattern().length()) {
return false;
}
dataFormat.setLenient(false);
try {
dataFormat.parse(inDate.trim());
} catch (ParseException e) {
return false;
}
return true;
}
}
五、Stream流工具类
public class StreamUtils {
private StreamUtils() {
}
public static <T, R> List<R> toList(List<T> srcList, Function<? super T, ? extends R> mapper) {
if (CollectionUtils.isEmpty(srcList)) {
return Lists.newArrayList();
}
return srcList.stream().map(mapper).collect(Collectors.toList());
}
public static <T, R> Set<R> toSet(List<T> srcList, Function<? super T, ? extends R> mapper) {
if (CollectionUtils.isEmpty(srcList)) {
return Sets.newHashSet();
}
return srcList.stream().filter(e -> mapper.apply(e) != null).map(mapper).collect(Collectors.toSet());
}
public static <T> int sum(List<T> srcList, ToIntFunction<? super T> toIntFunction) {
if (CollectionUtils.isEmpty(srcList)) {
return 0;
}
return srcList.stream().mapToInt(toIntFunction).sum();
}
public static <T, K, U> Map<K, U> toMap(List<T> srcList,
Function<? super T, ? extends K> mapper1,
Function<? super T, ? extends U> mapper2) {
if (CollectionUtils.isEmpty(srcList)) {
return new HashMap<>();
}
return srcList.stream().collect(Collectors.toMap(mapper1, mapper2));
}
public static <T, K, U> Map<K, U> toMap(List<T> srcList,
Function<? super T, ? extends K> mapper1,
Function<? super T, ? extends U> mapper2,
BinaryOperator<U> mergeFunction) {
if (CollectionUtils.isEmpty(srcList)) {
return new HashMap<>();
}
return srcList.stream().collect(Collectors.toMap(mapper1, mapper2, mergeFunction));
}
public static <T> List<T> filter(Collection<T> source, Predicate<T> predicate) {
if (CollectionUtils.isEmpty(source)) {
return new ArrayList<>(0);
}
return source.stream().filter(Objects::nonNull).filter(predicate).collect(Collectors.toList());
}
public static <T> T findAny(Collection<T> source, Predicate<T> predicate) {
if (CollectionUtils.isEmpty(source)) {
return null;
}
return source.stream().filter(Objects::nonNull).filter(predicate).findAny().orElse(null);
}
public static <T> boolean anyMatch(Collection<T> source, Predicate<T> predicate) {
if (CollectionUtils.isEmpty(source)) {
return false;
}
return source.stream().anyMatch(predicate);
}
public static <T, R> Map<R, List<T>> groupBy(List<T> srcList, Function<? super T, ? extends R> keyMapper) {
if (CollectionUtils.isEmpty(srcList)) {
return new HashMap<>();
}
return srcList.stream().collect(Collectors.groupingBy(keyMapper));
}
public static <T, V> V max(List<T> srcList, Function<? super T, ? extends Comparable<V>> keyMapper) {
if (CollUtil.isEmpty(srcList)) {
return null;
}
V result = null;
for (T t : srcList) {
if (keyMapper.apply(t) != null && (result == null || keyMapper.apply(t).compareTo(result) > 0)) {
result = (V) keyMapper.apply(t);
}
}
return result;
}
public static <T, V> V min(List<T> srcList, Function<? super T, ? extends Comparable<V>> keyMapper) {
if (CollUtil.isEmpty(srcList)) {
return null;
}
V result = null;
for (T t : srcList) {
if (keyMapper.apply(t) != null && (result == null || keyMapper.apply(t).compareTo(result) < 0)) {
result = (V) keyMapper.apply(t);
}
}
return result;
}
public static <T> boolean allMatch(Collection<T> collection, Predicate<T> predicate) {
if (CollUtil.isEmpty(collection)) {
return false;
}
return collection.stream().allMatch(predicate);
}
public static <T> List<T> distinct(Collection<T> source, Function<? super T, ?> keyExtractor) {
if (CollectionUtils.isEmpty(source)) {
return new ArrayList<>(0);
}
return source.stream().filter(distinctByKey(keyExtractor))
.collect(Collectors.toList());
}
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}