package com.tzld.piaoquan.recommend.model.produce.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

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

/**
 * @author dyp
 */
public class CommonCollectionUtils {
    public static <T, R> List<R> toList(Collection<T> list, Function<T, R> map) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream().map(map).collect(Collectors.toList());
    }

    public static <T, K, V> Map<K, V> toMap(List<T> list, Function<T, K> keyFunc, Function<T, V> valueFunc) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        return list.stream().collect(Collectors.toMap(keyFunc::apply, valueFunc::apply));
    }

    public static <T, K, V> Map<K, V> toMap(T[] list, Function<T, K> keyFunc, Function<T, V> valueFunc) {

        if (list == null || list.length == 0) {
            return Collections.emptyMap();
        }
        return Arrays.stream(list).collect(Collectors.toMap(keyFunc::apply, valueFunc::apply));
    }

    public static <K, V> Map<K, V> merge(Map<K, V> map1, Map<K, V> map2) {
        if (MapUtils.isEmpty(map1)) {
            return map2;
        }
        if (MapUtils.isEmpty(map2)) {
            return map1;
        }

        Map<K, V> map = new HashMap<>();
        map.putAll(map1);
        map.putAll(map2);
        return map;
    }
}
