package com.zzwtec.third.utils;

import org.apache.commons.lang.ArrayUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

/**
 * create by Jomchen on 2018/11/29
 */
public class ListUtil {
    /**
     * 判断List是否为空
     * @return
     */
    public static <T> boolean isEmpty(List<T> list){
        if(list ==null || list.size() == 0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 判断List是否不为空
     */
    public static <T> boolean notEmpty(List<T> list){
        return !isEmpty(list);
    }

    /**
     * 数组转List
     */
    public static <T> List<T> toList(T[] arr){
        List<T> list = new ArrayList<T>();
        Collections.addAll(list, arr);
        return list;
    }

    /**
     * list转字符串
     * @return
     */
    public static <T> String join(List<T> list,String join){
        StringBuilder sb = new StringBuilder();
        if(isEmpty(list)){
            return "";
        }
        for(T str : list){
            sb.append(join);
            sb.append(str);
        }
        return sb.substring(1);
    }

    /**
     * list转字符串
     * @return
     */
    public static <T> String join(List<T> list){
        return join(list,",");
    }

    /**
     * list转数组,实际上只能处理Object类型
     * @param list
     */

    public static Object[] toArray(List<Object> list){
        return list.toArray();
    }



    @SuppressWarnings("unchecked")
    public static <T> T[] toArray(List<T> list,Class<T> type){
        T[] a = (T[])java.lang.reflect.Array.newInstance(type,list.size());
        list.toArray(a);
        return a;
    }

    public static <F, O> List<O> transform(List<F> source, Function<F, O> function) {
        if (isEmpty(source)) {
            return null;
        }
        if (function == null) {
            throw new IllegalArgumentException("function is null");
        }
        List<O> target = new ArrayList<>(source.size());
        for (F f : source) {
            target.add(function.apply(f));
        }
        return target;
    }

    public static void add(List<Object> list, Object... objects) {
        if (list != null && !ArrayUtils.isEmpty(objects)) {
            Arrays.stream(objects).forEach(o -> list.add(o));
        }
    }
}
