package com.tzy.common.utils;

import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @program:
 * @description: 集合工具类
 * @author: Mr.Huang
 * @create:
 */
public class CollectionUtil {

    private static final String BLANK = "";
    private static final String apostrophe = "'";
    private static final String COMMA = ",";

    public static void main(String[] args) {
        //
        // ArrayList<Object> list = new ArrayList<>();
        // list.add("1");
        // list.add("2");
        // String s = listToString(list);
        // System.out.println(s);
        // System.out.println(list.toString());
        // String s1 = listToSqlInString(list);
        // System.out.println(s1);
        List<String> list2 = Arrays.asList("a", "b", "c", "d", "e");
        List<String> list1 = Arrays.asList("e", "f", "g", "h", "i", "d");
        Set<String> commonElements = getCommonElements(list1,list2);
        // 输出重复的元素
        System.out.println("重复的元素是:");
        for (String commonElement : commonElements) {
            System.out.println(commonElement);
        }
    }

    /**
     * 获取两个集合的交集
     * @param list1
     * @param list2
     * @return
     */
    public static Set<String> getCommonElements(List<String> list1, List<String> list2) {
        if (CollectionUtils.isEmpty(list1) || CollectionUtils.isEmpty(list2)) {
            return null;
        }
        Set<String> set1 = new HashSet<>(list1);
        Set<String> set2 = new HashSet<>(list2);
        Set<String> commonElements = new HashSet<>(set1);
        commonElements.retainAll(set2);
        return commonElements;
    }

    /**
     * 集合转换成逗号分隔的字符串,空集合返回空字符
     *
     * @param list
     * @return
     */
    public static String listToString(List list) {
        if (list == null || list.isEmpty()) {
            return BLANK;
        }

        return list.toString().replace("[", BLANK).replace("]", BLANK);
    }

    public static String listToSqlInString(List list) {
        if (list == null || list.isEmpty()) {
            return BLANK;
        }
        StringBuffer buf = new StringBuffer();
        list.forEach(s -> buf.append(apostrophe).append(s).append(apostrophe).append(COMMA));
        buf.setLength(buf.length() - 1);
        return buf.toString();
    }
}
