package com.tzld.longarticle.recommend.server.util;

import org.apache.commons.collections4.CollectionUtils;

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

/**
 * @author dyp
 */
public class CommonCollectionUtils {

    public static <T> List<T> iterableToList(Iterable<T> iterable) {
        List<T> list = new ArrayList<>();
        for (T element : iterable) {
            list.add(element);
        }
        return list;
    }

    public static <T, R> List<R> toList(List<T> list, Function<T, R> map) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream().map(map).collect(Collectors.toList());
    }

    public static <T, R> List<R> toListDistinct(List<T> list, Function<T, R> map) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream().map(map).distinct().collect(Collectors.toList());
    }


    public static <T, K, V> Map<K, V> toMap(Collection<T> col, Function<T, K> keyFunc, Function<T, V> valueFunc) {
        if (CollectionUtils.isEmpty(col)) {
            return Collections.emptyMap();
        }
        return col.stream().collect(Collectors.toMap(keyFunc::apply, valueFunc::apply, (u, v) -> v, HashMap::new));
    }

    public static <T, R> Set<R> toSet(Collection<T> col, Function<T, R> func) {
        if (CollectionUtils.isEmpty(col)) {
            return Collections.emptySet();
        }
        return col.stream()
                .map(c -> func.apply(c))
                .collect(Collectors.toSet());
    }

    public static <T> boolean contains(Collection<T> col, T ele) {
        if (CollectionUtils.isEmpty(col)) {
            return false;
        }
        return col.contains(ele);
    }
}
