All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dennisit.vplus.data.utils.CollectionUtils Maven / Gradle / Ivy

There is a newer version: 2.0.8
Show newest version
/*--------------------------------------------------------------------------
 *  Copyright (c) 2010-2020, Elon.su All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the elon developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: Elon.su, you can also mail [email protected]
 *--------------------------------------------------------------------------
 */
package com.github.dennisit.vplus.data.utils;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Elon.su on 17/5/29.
 */
@Slf4j
public class CollectionUtils {

    /**
     * 集合是否为空
     *
     * @param coll 目标集合
     * @return 不为空返回true
     */
    public static boolean isNotEmpty(final Collection coll) {
        return !isEmpty(coll);
    }

    /**
     * 集合是否为空
     *
     * @param coll 目标集合
     * @return 为空返回true
     */
    public static boolean isEmpty(final Collection coll) {
        return org.apache.commons.collections4.CollectionUtils.isEmpty(coll);
    }


    /**
     * Concatenates 2 arrays
     *
     * @param one   数组1
     * @param other 数组2
     * @return 新数组
     */
    public static String[] concat(String[] one, String[] other) {
        return concat(one, other, String.class);
    }

    /**
     * Concatenates 2 arrays
     *
     * @param one   数组1
     * @param other 数组2
     * @param clazz 数组类
     * @param    泛型
     * @return 新数组
     */
    public static  T[] concat(T[] one, T[] other, Class clazz) {
        T[] target = (T[]) Array.newInstance(clazz, one.length + other.length);
        System.arraycopy(one, 0, target, 0, one.length);
        System.arraycopy(other, 0, target, one.length, other.length);
        return target;
    }

    /**
     * 不可变 Set
     *
     * @param es  对象
     * @param  泛型
     * @return 集合
     */
    @SafeVarargs
    public static  Set ofImmutableSet(E... es) {
        Objects.requireNonNull(es, "args es is null.");
        return Arrays.stream(es).collect(Collectors.toSet());
    }

    /**
     * 不可变 List
     *
     * @param es  对象
     * @param  泛型
     * @return 集合
     */
    @SafeVarargs
    public static  List ofImmutableList(E... es) {
        Objects.requireNonNull(es, "args es is null.");
        return Arrays.stream(es).collect(Collectors.toList());
    }


    /**
     * 对list元素进行转化。
     *
     * @param srcList 源list
     * @param fun     转换函数
     * @param      源类型
     * @param      目标类型
     * @return 转换后的list
     */
    public static  List transform(Collection srcList, Function fun) {
        if (isEmpty(srcList)) {
            return Collections.EMPTY_LIST;
        }
        List descList = new ArrayList<>(srcList.size());
        srcList.forEach(x -> {
            descList.add(fun.apply(x));
        });
        return descList;
    }

    /**
     * Map按照Value进行排期
     *
     * @param map 目标map
     * @param  key元素
     * @param  value元素
     * @return 排序后的结果
     */
    public static > Map sortByValue(Map map) {
        List> list = new LinkedList>(map.entrySet());
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        Map result = new LinkedHashMap();
        for (Map.Entry entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }


    /**
     * 将多个数组合并在一起
     * 忽略null的数组
     *
     * @param arrays 数组
     * @param     泛型
     * @return 合并后的数组
     */
    public static  T[] addAll(T[]... arrays) {
        if (arrays.length == 1) {
            return arrays[0];
        }

        int length = 0;
        for (T[] array : arrays) {
            if (array == null) {
                continue;
            }
            length += array.length;
        }
        T[] result = newArray(arrays.getClass().getComponentType().getComponentType(), length);

        length = 0;
        for (T[] array : arrays) {
            if (array == null) {
                continue;
            }
            System.arraycopy(array, 0, result, length, array.length);
            length += array.length;
        }
        return result;
    }


    /**
     * 新建一个空数组
     *
     * @param componentType 元素类型
     * @param newSize       大小
     * @param            泛型
     * @return 新数组
     */
    @SuppressWarnings("unchecked")
    public static  T [] newArray(Class componentType, int newSize) {
        return (T[]) Array.newInstance(componentType, newSize);
    }

    /**
     * 将集合中的内容写入CSV文件
     *
     * @param collection   要写入文件的集合集合
     * @param pathWithName CSV文件路径,带文件名
     * @param charset      字符集
     */
    public static void toCSV(Collection collection, String pathWithName, String charset) {
        try {
            PrintWriter writer = FileWriteUtils.getPrintWriter(pathWithName, charset, false);
            for (String line : collection) {
                log.debug("写入:" + line);
                writer.println(line);
            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}