package com.malk.utils;

import cn.hutool.core.util.ObjectUtil;

import java.util.*;
import java.util.stream.Collectors;

public abstract class UtilList {

    // 访问安全, 避免空指针访问访问属性异常
    public static boolean isEmpty(List list) {
        return ObjectUtil.isNull(list) || list.isEmpty();
    }

    public static boolean isNotEmpty(List list) {
        return !isEmpty(list);
    }

    public static boolean isEmpty(Object[] list) {
        return ObjectUtil.isNull(list) || list.length == 0;
    }

    public static boolean isNotEmpty(Object[] list) {
        return !isEmpty(list);
    }

    public static Object getLast(List list) {
        if (isEmpty(list)) return null;
        return list.get(list.size() - 1);
    }

    public static Object getLast(Object[] list) {
        if (isEmpty(list)) return null;
        return list[list.length - 1];
    }

    /**
     * Arrays.asList 不可变, asList 为可变 [Set -> new ArrayList<>(Map.keySet())]
     */
    public static List asList(Object... a) {
        List tList = new ArrayList<>();
        tList.addAll(Arrays.asList(a));
        return tList;
    }

    /// collection.frequency方法，可以统计出某个对象在collection中出现的次数
    private static Map _frequency(List list) {
        Set uniqueWords = new HashSet<>(list);
        int max = 0;
        Object val = null;

        for (Object word : uniqueWords) {
            int num = Collections.frequency(list, word);
            if (num > max) {
                max = num;
                val = word;
            }
        }
        return UtilMap.map("max, val", max, val);
    }

    /**
     * 某个对象在collection中出现最多次对象
     */
    public static Object maxFrequencyObject(List list) {
        return _frequency(list).get("val");
    }

    /**
     * 某个对象在collection中出现最多次次数
     */
    public static Object maxFrequencyCounty(List list) {
        return _frequency(list).get("max");
    }

    /**
     * 忽略集合内, map属性为0字段 [列表/导出]
     */
    public static List<Map> ignoreListMapZero(List<Map> list) {
        return list.stream().map(item -> {
            Map data = new HashMap();
            for (Object key : item.keySet()) {
                UtilMap.putNotZero(data, key.toString(), item.get(key));
            }
            return data;
        }).collect(Collectors.toList());
    }

    /// 判定集合是否包含另一个集合任一元素
    public static boolean isContainsOne(List<String> oneList, List<String> otherList) {
        for (String one : otherList) {
            boolean contains = oneList.contains(one);
            if (contains) {
                return true;
            }
        }
        return false;
    }

    // 判断集合中是否存在重复对象
    public static boolean isDistinct(List<Map> dataList, String prop) {
        List dList = dataList.stream().map(item -> item.get(prop)).collect(Collectors.toList());
        return dList.stream().distinct().count() != dList.size();
    }
}
