CollectionUtils集合常用方法
前言
使用Java自带的方法可以极大地提升代码可读性,代码规范性。
1、CollectionUtils.isEmpty(@Nullable Collection<?> collection);
作用:判断集合是否为null或者是否为空
public static boolean isEmpty(@Nullable Collection<?> collection) { return (collection == null || collection.isEmpty()); } eg: List<String> list = new ArrayList<>(); if (CollectionUtils.isEmpty(list)) { // doSomthing }
2、CollectionUtils.arrayToList(@Nullable Object source);
作用:将一个数组转换为一个包装类型的List集合
public static List<?> arrayToList(@Nullable Object source) { return Arrays.asList(ObjectUtils.toObjectArray(source)); } eg: int[] arr = new int[]{2, 5, 8}; List<?> objects = CollectionUtils.arrayToList(arr);
3、CollectionUtils.mergeArrayIntoCollection(@Nullable Object array, Collection<E> collection);
作用:将给定的数组合并到给定的集合中
@SuppressWarnings("unchecked") public static <E> void mergeArrayIntoCollection(@Nullable Object array, Collection<E> collection) { Object[] arr = ObjectUtils.toObjectArray(array); for (Object elem : arr) { collection.add((E) elem); } } eg: int[] arr = new int[]{2, 5, 8}; List<Integer> list = new ArrayList<>(); CollectionUtils.mergeArrayIntoCollection(arr, list);
下一篇:
查看 jdk 版本及安装路径